php 将 key=>value 对添加到具有条件的现有数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11461781/
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 00:33:56  来源:igfitidea点击:

Adding key=>value pair to existing array with condition

phparraysassociative-array

提问by Yeak

Im trying to add a key=>value to a existing array with a specific value.

我试图将 key=>value 添加到具有特定值的现有数组。

Im basically looping through a associative array and i want to add a key=>value foreach array that has a specific id:

我基本上循环遍历一个关联数组,我想为具有特定 id 的每个数组添加一个 key=>value:

ex:

前任:

[0] => Array
    (
        [id] => 1
        [blah] => value2

    )

[1] => Array
    (
        [id] => 1
        [blah] => value2
    )

I want to do it so that while

我想这样做,以便同时

foreach ($array as $arr) {

     while $arr['id']==$some_id {

            $array['new_key'] .=$some value
            then do a array_push
      }    
}

so $some_value is going to be associated with the specific id.

所以 $some_value 将与特定的 id 相关联。

回答by Tucker

The while loop doesn't make sense since keys are unique in an associative array. Also, are you sure you want to modify the array while you are looping through it? That may cause problems. Try this:

while 循环没有意义,因为键在关联数组中是唯一的。另外,您确定要在循环遍历数组时修改它吗?这可能会导致问题。尝试这个:

$tmp = new array();
foreach ($array as $arr) {

     if($array['id']==$some_id) {
            $tmp['new_key'] = $some_value;
      }    
}


array_merge($array,$tmp);

A more efficient way is this:

更有效的方法是这样的:

if(in_array($some_id,$array){
  $array['new_key'] = $some_value;
}

or if its a key in the array you want to match and not the value...

或者如果它是您要匹配的数组中的键而不是值...

if(array_key_exists($some_id,$array){
      $array['new_key'] = $some_value;
    }

回答by Delford Chaffin

When you use:

当您使用:

foreach($array as $arr){
    ...
}

... the $arr variable is a local copy that is only scoped to that foreach. Anything you add to it will not affect the $array variable. However, if you call $arr by reference:

... $arr 变量是一个本地副本,仅适用于该 foreach。您添加的任何内容都不会影响 $array 变量。但是,如果您通过引用调用 $arr:

foreach($array as &$arr){ // notice the &
    ...
}

... now if you add a new key to that array it will affect the $array through which you are looping.

...现在,如果您向该数组添加一个新键,它将影响您正在循环的 $array 。

I hope I understood your question correctly.

我希望我正确理解了你的问题。

回答by Besnik

If i understood you correctly, this will be the solution:

如果我理解正确,这将是解决方案:

foreach ($array as $arr) {
  if ($arr['id'] == $some_id) {
     $arr[] = $some value;
     // or: $arr['key'] but when 'key' already exists it will be overwritten
  }
}