简体   繁体   English

带有键值对的array_push()

[英]array_push() with key value pair

I have an existing array to which I want to add a value.我有一个想要添加值的现有数组。

I'm trying to achieve that using array_push() to no avail.我正在尝试使用array_push()来实现这一点,但无济于事。

Below is my code:下面是我的代码:

$data = array(
    "dog" => "cat"
);

array_push($data['cat'], 'wagon');

What I want to achieve is to add cat as a key to the $data array with wagon as value so as to access it as in the snippet below:我想要实现的是将cat作为键添加到$data数组中,并以wagon作为值,以便像下面的代码片段一样访问它:

echo $data['cat']; // the expected output is: wagon

How can I achieve that?我怎样才能做到这一点?

那么拥有:

$data['cat']='wagon';

如果您需要添加多个 key=>value,请尝试此操作。

$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
$data['cat'] = 'wagon';

这就是将键和值添加到数组所需的全部内容。

You don't need to use array_push() function, you can assign new value with new key directly to the array like..您不需要使用 array_push() 函数,您可以使用新键直接将新值分配给数组,例如..

$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);


Output:

   Array(
     [color1] => red
     [color2] => blue
     [color3] => green
   )

For Example:例如:

$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');

For changing key value:更改键值:

$data['firstKey'] = 'changedValue'; 
//this will change value of firstKey because firstkey is available in array

output:输出:

Array ( [firstKey] => changedValue [secondKey] => secondValue )数组( [firstKey] => changedValue [secondKey] => secondValue )

For adding new key value pair:添加新的键值对:

$data['newKey'] = 'newValue'; 
//this will add new key and value because newKey is not available in array

output:输出:

Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue )数组 ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue)

Array['key'] = value;数组['key'] = 值;

$data['cat'] = 'wagon';

This is what you need.这就是你所需要的。 No need to use array_push() function for this.无需为此使用 array_push() 函数。 Some time the problem is very simple and we think in complex way :) .有时问题很简单,我们以复杂的方式思考:)。

<?php
$data = ['name' => 'Bilal', 'education' => 'CS']; 
$data['business'] = 'IT';  //append new value with key in array
print_r($data);
?>

Result结果

Array
(
    [name] => Bilal
    [education] => CS
    [business] => IT
)

Just do that:就这样做:

$data = [
    "dog" => "cat"
];

array_push($data, ['cat' => 'wagon']);

*In php 7 and higher, array is creating using [], not () *在 php 7 及更高版本中,数组是使用 [] 创建的,而不是 ()

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

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