2015-04-06 44 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'); 
?> 

其實我看到我太慢了,但在這裏你得到了非修改遞歸函數的樣本:)