(多维数组)更改索引为某个字符串的所有值


(multidimensional array) Change all values where index is a certain string

我正在使用以下数组,我想将所有没有值的"price"键设置为0。

如果数组的深度是无限的,我该如何实现这一点?

非常感谢!

Array
(
    [0] => Array
    (
        [random_key0] => Array
            (
                [name] => Foo
                [price] => 25
            )
        [random_key1] => Array
            (
                [name] => Bar
                [price] => 
            )
    [1] => Array
    (
        [name] => 125
        [price] =>
    )
    [2] => Array
    (
        [another_key0] => Array
            (
                [name] => Foo
                [options] => Options here
                [special0] => Array
                    (
                        [name] => Special Name
                        [price] =>
                    )
                [special1] => Array
                    (
                        [name] => Special 2
                        [price] => 120
                    )
              )
        )
  )

您可以使用一个"walking"函数来实现这一点,该函数会调用自己,直到所有元素都完成为止:

<?php
$test = array(
    array(
        "random_key0" => array("name"=>"foo","price"=>25), 
        "random_key1" => array("name"=>"Bar","price"=>"")
    ),
    array("name"=>125,"price"=>""), 
    array("another_key0" => array(
        "name" => "foo",
        "options" => "Options here",
        "special0" => array("name"=>"Special Name","price"=>""),
        "special1" => array("name"=>"Special 2","price"=>120),
    ))
);
function test_alter(&$item, $key)
{
    if ($key=="price" && empty($item))
        $item = 0;
}
function test_print($item2, $key)
{
    echo "$key. $item2<br>'n";
}
echo "Before ...:'n";
array_walk_recursive($test, 'test_print');
// now actually modify values
array_walk_recursive($test, 'test_alter');
echo "... and afterwards:'n";
array_walk_recursive($test, 'test_print');
?>

事实上,我发现我太慢了,但这里也有不修改递归函数的示例:)

您可以使用array_walk_recurive,例如:

<?php
function update_price(&$item, $key) {
    if ($key == 'price' && !$item) {
        $item = 0;
    }
}
$test = array('key1' => array('price' => null, 'test' => 'abc', 'sub' => array('price' => 123), 'sub2' => array('price' => null)));
array_walk_recursive($test, 'update_price');
print_r($test);