我正在处理如下数组,我想设置所有"价格"没有价值的键,为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
)
)
)
)
答案 0 :(得分:1)
您可以使用“行走”功能执行此操作,该功能会调用自身,直到所有元素都通过:
<?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');
?>
实际上我看到我太慢了,但是你在这里也得到了非修改递归函数的样本:)
答案 1 :(得分:0)
您可以使用array_walk_recursive,例如:
<?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);