无法将项目添加为数组中的第一个项目 - 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');

我的这一行代码返回一个数组作为键=>值对数组。因此,如果我在屏幕上转储$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"

我想做的是将新项目作为此数组的第一个项目前置/添加所以我尝试用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返回数组中的元素数,这就是获取数组计数的原因

array_unshift第一个参数中接收一个引用数组:

array_unshift($this->data['dropdown_items'], "Please select a category");

如果将返回值分配给数组,它将替换为数组中的元素数 (int)。