在数组的开头插入一个键值对在php中

时间:2010-11-23 10:14:46

标签: php

array_unshift ($ids,$product_id => $catalog_tag);

如果我把

array($product_id => $catalog_tag) 

会工作,但不会将$ product_id添加为关键.. 我想在开始时添加它

3 个答案:

答案 0 :(得分:27)

使用array_reverse反转数组,然后使用array_push将元素推送到数组的末尾,然后再次反转数组。您将在数组的开头有新元素。

$arrayone=array("newkey"=>"newvalue") + $arrayone; 

答案 1 :(得分:10)

$ids = array(0 => "bla bla", 1 => "bla bla", 2 => "bla bla", 3 => "bla bla")
foreach($ids as $key => $val){
    $key = "$key";
}
unset(current($ids));
$ids = array_merge(array("$product_id" => $catalog_tag), $ids);

我认为应该有效

答案 2 :(得分:2)

See this answer.

It refers to moving an already existing element to the beginning of the array, but it would also have the desired result if it doesn't exist.