2015-04-06 43 views
0

我正在处理数组,例如以下内容,并且我想将所有没有数值的“价格”键设置为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

我可以推荐你,而不是使用循环来将价格转换为int/float。空将变成0 .. – Svetoslav 2015-04-06 12:20:34

+0

你从哪里获取源数据?这样做会容易得多。甚至在展览会上,如果这将做的工作。 – 2015-04-06 12:22:01

回答

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); 
+0

这很好,谢谢! – Philex 2015-04-06 12:44:49

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'); 
?> 

其实我看到我太慢了,但在这里你得到了非修改递归函数的样本:)