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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5783750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:28:50  来源:igfitidea点击:

PHP - add item to beginning of associative array

php

提问by teepusink

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
)
Array
(
    [key1] => value1
    [key2] => value2
    [key0] => value0
)

How do I make that to be

我如何做到这一点

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

Thanks,
Tee

谢谢,
Tee

回答by Felix Kling

You could use the unionoperator:

您可以使用联合运算符

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

or array_merge.

array_merge

回答by outis

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.

回答by Mark Baker

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

回答by Tomek

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

    return $array;
}

回答by James C

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

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