2016-12-24 49 views
4

我需要從PHP中的數組獲取每個鍵值對。結構是不同的,也不是可規劃的,例如一個鍵可能包含一個附加數組等等(多維數組?)。我想調用的函數的任務是從值中替換特定的字符串。問題是功能foreach,each,...只使用主鍵和值。如何從PHP陣列獲取每個鍵值對

是否存在具有foreach功能的功能鍵/值?

+2

http://php.net/manual/en/function.array-walk-recursive.php - 它不會涵蓋所有情況(更復雜的結構?)...但是,應該有所幫助 - 基本上,你需要遞歸 - >檢查值是數組,再次調用函數等,等等... http:// stackoverflow。com/questions/6088687/recursive-loop-for-multidimenional-arrays – sinisake

+0

@sinisake是否有可能檢索完整的var-「path」/父鍵,例如當我的代碼是'$ fruits = ['sweet'=> [「hi」=>「nett」],'sour'=>'lemon'];函數test_print($ item,$ key) { echo「$ key holds $ item \ n」; } array_walk_recursive($ fruits,'test_print');'我得到另一個路徑是哪個鍵的含義? $ fruits [「sweet」] [「hi」] – HelloToYou

+0

昨天有人有類似的問題:http://stackoverflow.com/questions/41284689/iterate-through-multiple-array-and-execute-function/41284991#41284991請檢查最新的答案,它應該有所幫助。 – sinisake

回答

1

這種任務的常用方法是使用遞歸函數

讓我們走一步看一步:

首先,你需要的foreach控制語句...

http://php.net/manual/en/control-structures.foreach.php

..that讓你解析關聯數組事先不知道密鑰的名字。

然後is_arrayis_string(最終is_objectis_integer ...),讓你檢查每一個值的類型,這樣就可以正常行動。

http://php.net/manual/en/function.is-array.php

http://php.net/manual/en/function.is-string.php

如果您查找的字符串進行操作,然後你就替換任務

如果你發現一個數組功能本身回憶剛剛經過解析的陣列。

這樣,原始數組將被解析到最深層次,而不會丟失和鍵值對。


例子:

function findAndReplaceStringInArray($theArray) 
{ 
    foreach ($theArray as $key => $value) 
    { 
     if(is_string($theArray[ $key ]) 
     { 
      // the value is a string 
      // do your job... 

      // Example: 
      // Replace 'John' with 'Mike' if the `key` is 'name' 

      if($key == 'name' && $theArray[ $key ] == "John") 
      { 
       $theArray[ $key ] = "Mike"; 
      } 
     } 
     else if(is_array($theArray[ $key ]) 
     { 
      // treat the value as a nested array 

      $nestedArray = $theArray[ $key ]; 

      findAndReplaceStringInArray($nestedArray); 
     } 
    } 
} 
0

您可以創建一個遞歸函數來對待它。

function sweep_array(array $array) 
{ 
    foreach($array as $key => $value){ 

     if(is_array($value)) 
     { 
      sweep_array($value); 
     } 
     else 
     { 
      echo $key . " => " . $value . "<br>"; 
     } 
    } 
} 
1

沒有內置的功能如您所願,但你可以使用RecursiveIteratorIterator與之相適應,走遞歸的多維數組,並與國旗RecursiveIteratorIterator::SELF_FIRST,你會得到相同級別的所有元素的作品首先,在深入之前,不要錯過任何一對。

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST); 

foreach ($iterator as $key => $item) { 
    // LOGIC 
} 
相關問題