简体   繁体   English

PHP-如何将键=>值添加到多维数组的特定部分?

[英]PHP - How do I add a key => value to a specific part of an multidimensional array?

How would I insert a key => value pair into the midst of a nested array? 如何将键=>值对插入嵌套数组的中间?

example: 例:

array
  1 => string 'a' (length=1)
  2 => string 'b' (length=1)
  3 => 
    array
      'this' => string 'that' (length=4)
      'meh' => string 'foo' (length=3)
      'blah' => 
        array
          'a' => int 1
          'b' => int 2
  4 => 
    array
      'this' => string 'that' (length=4)
      'meh' => string 'foo' (length=3)
      'blah' => 
        array
          'a' => int 1
          'b' => int 2

How would I add x=>1 to every second level of array... so I would get this: 我如何将x=>1添加到数组的每一第二级...所以我将得到以下信息:

 array
  1 => string 'a' (length=1)
  2 => string 'b' (length=1)
  3 => 
    array
      'this' => string 'that' (length=4)
      'meh' => string 'foo' (length=3)
      'blah' => 
        array
          'a' => int 1
          'b' => int 2
      'x' => int 1 //Here's the added bit
  4 => 
    array
      'this' => string 'that' (length=4)
      'meh' => string 'foo' (length=3)
      'blah' => 
        array
          'a' => int 1
          'b' => int 2
       'x' => int 1 //Here's the added bit
$array[3]['x'] = 1;
$array[4]['x'] = 1;

Or, if you were looking for something automated on an array of indefinite length: 或者,如果您要查找不确定长度的数组中的自动化内容:

foreach ($array as &$node) {
    if (is_array($node)) {
        $node['x'] = 1;
    }
}
if(!is_array($array1['property']))
{
    $array1['property'] = array();
}

$array1['property']['x'] = 1;

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

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