简体   繁体   English

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

[英]Insert at start of array a key-value pair in php

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

if i put如果我把

array($product_id => $catalog_tag) 

would work but wont add $product_id as key.. I want to add it at the start会工作,但不会添加 $product_id 作为键..我想在开始时添加它

Use array_reverse to reverse the array and then push the element to end of array using array_push and then reverse the array again.使用array_reverse反转数组,然后使用array_push将元素推送到数组末尾,然后再次反转数组。 You will have the new element at beginning of the array.您将在数组的开头拥有新元素。

or或者

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

This code takes your array noting that it's using integer keys for your array so these will always be the array order, so we convert them to string keys and this prevents the key's acting as the order of the array.这段代码需要你的数组,注意到它为你的数组使用整数键,所以这些将始终是数组顺序,所以我们将它们转换为字符串键,这可以防止键充当数组的顺序。 we then create the a new array with your value and append all values from your existing array to the end.然后,我们使用您的值创建一个新数组,并将现有数组中的所有值附加到末尾。

note that the product ID is converted to a string again to prevent the integer key from ordering the array.请注意,产品 ID 再次转换为字符串,以防止整数键对数组进行排序。

$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);

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.它是指将已经存在的元素移动到数组的开头,但如果它不存在,它也会有所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM