简体   繁体   English

在PHP中同时推送键和值时如何使用array_push

[英]how to use array_push when pushing both key and value in PHP

I have an empty array. 我有一个空数组。 I am able to push values using 我能够使用

array_push($list, item[0]);

But how do I push both key and value. 但是我如何同时推动关键和价值。

array_push($list[$key], $item[0])

this does not work. 这行不通。

$list['key']=$item[0];

should work. 应该管用。

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function. 注意:如果使用array_push()将一个元素添加到数组中,则最好使用$ array [] =,因为这样可以节省调用函数的开销。

If you want to maintain the key => value pairs you could use array_merge function. 如果要维护键=>值对,则可以使用array_merge函数。

$arr1 = array('apple' => 'fruit', 'banana' => 'fruit');
$arr2 = array('turnip' => 'vegetable', 'mushroom' => 'other');

$newArray = array_merge($arr1,$arr2)

This will return: 这将返回:

Array
(
    [apple] => fruit
    [banana] => fruit
    [turnip] => vegetable
    [mushroom] => other
)

But if two keys are the same in two arrays the one in the first array will be overwritten by the value in the second. 但是,如果两个数组中的两个键相同,则第一个数组中的一个将被第二个数组中的值覆盖。

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

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