2011-05-22 134 views
2

我基本上想用str_replace函數一個multidimenional陣列的所有值。我似乎無法解決如何爲多維數組做這件事。當數值是一個數組時,我會遇到一點困難,它似乎只是一個永無止境的循環。即時通訊新的PHP,所以emaples會有所幫助。多維數組的遞歸循環?

function _replace_amp($post = array(), $new_post = array()) 
{ 
    foreach($post as $key => $value) 
    { 
     if (is_array($value)) 
     { 
      unset($post[$key]); 
      $this->_replace_amp($post, $new_post); 
     } 
     else 
     { 
      // Replace :amp; for & as the & would split into different vars. 
      $new_post[$key] = str_replace(':amp;', '&', $value); 
      unset($post[$key]); 
     } 
    } 

    return $new_post; 
} 

感謝

+0

讓我們看看你想出什麼用至今。 – amccormack 2011-05-22 14:54:24

回答

4

這是錯誤的,將你置於一個永無休止的循環:

$this->_replace_amp($post, $new_post); 

你並不需要發送new_post作爲參數,並且你也想爲每個遞歸問題較小。改變你的功能是這樣的:

function _replace_amp($post = array()) 
{ 
    $new_post = array(); 
    foreach($post as $key => $value) 
    { 
     if (is_array($value)) 
     { 
      unset($post[$key]); 
      $new_post[$key] = $this->_replace_amp($value); 
     } 
     else 
     { 
      // Replace :amp; for & as the & would split into different vars. 
      $new_post[$key] = str_replace(':amp;', '&', $value); 
      unset($post[$key]); 
     } 
    } 

    return $new_post; 
} 
+0

謝謝,我可以看到我哪裏去錯了。 – Chapp 2011-05-22 15:12:41

3

... array_walk_recursive怎麼了?

<?php 
$sweet = array('a' => 'apple', 'b' => 'banana'); 
$fruits = array('sweet' => $sweet, 'sour' => 'lemon'); 

function test_print($item, $key) 
{ 
    echo "$key holds $item\n"; 
} 

array_walk_recursive($fruits, 'test_print'); 
?> 
+0

因爲你eggsample如果添加一個嵌套層次:'$水果= [ '甜'=> $甜, '酸'=> '檸檬', 'its_not'=> [ 'recursive_depth'];'在這種情況下,你沒有得到正確的鍵「its_not」 - 它給你'0',預計'its_not' - 或者正如人說***此功能僅探訪葉節點***(php.net - 他笑caplocked它) – JREAM 2017-05-16 18:37:13