5

我有一个二维数组:

$test = array(
    "foo" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
    "bar" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
    "baz" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    )
);

我想在外部数组的每个元素中添加一个以'd'值命名的字段4,以便生成的数组变为:

array(
    "foo" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3,
        'd' => 4
    ),
    "bar" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3,
        'd' => 4
    ),
    "baz" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3,
        'd' => 4
    )
)

我试过这个:

foreach ( $test as $elem ) 
{
    $elem['d'] = 4;
}

这是行不通的。我做错了什么,我怎样才能做到这一点?

4

3 回答 3

9

数组和原语在 PHP 中是按值传递的(尽管对象是通过引用传递的)。在循环中克服此问题的一种方法是在foreach循环中通过引用访问子数组:

// Call $elem by reference with &
foreach ( $test as &$elem ) {
    $elem['d'] = 4;
}

print_r($test);
array(3) {
  ["foo"]=>
  array(4) {
    ["a"]=>
    int(1)
    ["b"]=>
    int(2)
    ["c"]=>
    int(3)
    ["d"]=>
    int(4)
  }
  ...
}
于 2012-10-31T00:17:42.633 回答
3
$test = array(
    "foo" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
    "bar" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
    "baz" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    )
);

foreach($test as $key => $val)
    $test[$key]['d'] = 4;

print_r($test);
于 2012-10-31T00:18:46.600 回答
0

您可以利用 php 函数和回调:

array_walk($test, function ( & $value) {                                                                                                                                                            
     $value['d'] = 4;
}); 
于 2016-02-23T17:53:09.897 回答