无法将项目添加为数组中的第一项 - php array_unshift()
Can't add an item as first item in array - php array_unshift()
您好,我需要一些帮助。
// categories for dropdown
$this->data['dropdown_items'] = $this->category_model->get_key_value('id', 'category_name');
我的这行代码returns一个数组作为键=>值对数组。所以如果我在屏幕上转储 $this->data['dropdown_items'] 我得到这个:
array(8) {
[1] => "cinemas"
[5] => "theaters"
[7] => "night life"
[6] => "restaurants"
[4] => "food"
[2] => "night clubs"
[3] => "opera"
[8] => "misc"
}
i.e [id] => "the category name"
我想做的是 prepend/add 作为这个数组的第一个新项目
所以我尝试用 array_unshift() 函数添加它:
$this->data['dropdown_items'] = array_unshift($this->data['dropdown_items'], "Please select a category");
这就是我想要得到的:
array(8) {
[0] => "Please select a category"
[1] => "cinemas"
[5] => "theaters"
[7] => "night life"
[6] => "restaurants"
[4] => "food"
[2] => "night clubs"
[3] => "opera"
[8] => "misc"
}
但是当我转储 $this->data['dropdown_items'] 时,我得到以下内容
int(9)
有什么问题吗?
替换此
$this->data['dropdown_items'] = array_unshift($this->data['dropdown_items'], "Please select a category");
和
array_unshift($this->data['dropdown_items'], "Please select a category");
array_unshit returns 数组中元素的数量,这就是为什么你得到数组计数
array_unshift 在第一个参数中接收一个引用数组:
array_unshift($this->data['dropdown_items'], "Please select a category");
如果您将 return 值分配给数组,它将替换为数组中元素的数量 (int)。
您好,我需要一些帮助。
// categories for dropdown
$this->data['dropdown_items'] = $this->category_model->get_key_value('id', 'category_name');
我的这行代码returns一个数组作为键=>值对数组。所以如果我在屏幕上转储 $this->data['dropdown_items'] 我得到这个:
array(8) {
[1] => "cinemas"
[5] => "theaters"
[7] => "night life"
[6] => "restaurants"
[4] => "food"
[2] => "night clubs"
[3] => "opera"
[8] => "misc"
}
i.e [id] => "the category name"
我想做的是 prepend/add 作为这个数组的第一个新项目 所以我尝试用 array_unshift() 函数添加它:
$this->data['dropdown_items'] = array_unshift($this->data['dropdown_items'], "Please select a category");
这就是我想要得到的:
array(8) {
[0] => "Please select a category"
[1] => "cinemas"
[5] => "theaters"
[7] => "night life"
[6] => "restaurants"
[4] => "food"
[2] => "night clubs"
[3] => "opera"
[8] => "misc"
}
但是当我转储 $this->data['dropdown_items'] 时,我得到以下内容
int(9)
有什么问题吗?
替换此
$this->data['dropdown_items'] = array_unshift($this->data['dropdown_items'], "Please select a category");
和
array_unshift($this->data['dropdown_items'], "Please select a category");
array_unshit returns 数组中元素的数量,这就是为什么你得到数组计数
array_unshift 在第一个参数中接收一个引用数组:
array_unshift($this->data['dropdown_items'], "Please select a category");
如果您将 return 值分配给数组,它将替换为数组中元素的数量 (int)。