PHP -将项目添加到关联数组的开头[duplicate]

时间:2022-08-26 14:07:17

This question already has an answer here:

这个问题已经有了答案:

How can I add an item to the beginning of an associative array? For example, say I have an array like this:

如何向关联数组的开头添加项?例如,假设我有一个这样的数组:

$arr = array('key1' => 'value1', 'key2' => 'value2');

When I add something to it as in $arr['key0'] = 'value0';, I get:

当我在$arr['key0'] = 'value0'中添加一些东西时,我得到:

Array
(
    [key1] => value1
    [key2] => value2
    [key0] => value0
)

How do I make that to be

我该怎么做呢

Array
(
    [key0] => value0
    [key1] => value1
    [key2] => value2
)

Thanks,
Tee

谢谢,三通

5 个解决方案

#1


191  

You could use the union operator:

您可以使用union操作符:

$arr1 = array('key0' => 'value0') + $arr1;

or array_merge.

或array_merge。

#2


19  

One way is with array_merge:

一种方法是array_merge:

<?php
$arr = array('key1' => 'value1', 'key2' => 'value2');
$arr = array_merge(array('key0' => 'value0'), $arr);

Depending on circumstances, you may also make use of ksort.

根据具体情况,还可以使用ksort。

#3


7  

$array = array('key1' => 'value1', 'key2' => 'value2');
array_combine(array_unshift(array_keys($array),'key0'),array_unshift(array_values($array),'value0'))

#4


2  

If you don't want to merge the arrays you could just use ksort() on the array before iterating over it.

如果不希望合并数组,可以在迭代数组之前在数组上使用ksort()。

#5


2  

function unshift( array & $array, $key, $val)
{
    $array = array_reverse($array, 1);
    $array[$key] = $val;
    $array = array_reverse($array, 1);

    return $array;
}

#1


191  

You could use the union operator:

您可以使用union操作符:

$arr1 = array('key0' => 'value0') + $arr1;

or array_merge.

或array_merge。

#2


19  

One way is with array_merge:

一种方法是array_merge:

<?php
$arr = array('key1' => 'value1', 'key2' => 'value2');
$arr = array_merge(array('key0' => 'value0'), $arr);

Depending on circumstances, you may also make use of ksort.

根据具体情况,还可以使用ksort。

#3


7  

$array = array('key1' => 'value1', 'key2' => 'value2');
array_combine(array_unshift(array_keys($array),'key0'),array_unshift(array_values($array),'value0'))

#4


2  

If you don't want to merge the arrays you could just use ksort() on the array before iterating over it.

如果不希望合并数组,可以在迭代数组之前在数组上使用ksort()。

#5


2  

function unshift( array & $array, $key, $val)
{
    $array = array_reverse($array, 1);
    $array[$key] = $val;
    $array = array_reverse($array, 1);

    return $array;
}