2013-06-19 115 views
1

所有元素的路徑和值考慮任意形式和嵌套深度的關聯數組,例如:獲取嵌套關聯數組

$someVar = array(
    'name'  => 'Dotan', 
    'age'  => 35, 
    'children' => array(
     0 => array(
      'name' => 'Meirav', 
      'age' => 6, 
     ), 
     1 => array(
      'name' => 'Maayan', 
      'age' => 4, 
     ) 
    ), 
    'dogs' => array('Gili', 'Gipsy') 
); 

我想將此轉換爲的路徑和值關聯數組:

$someVar = array(
    'name'   => 'Dotan', 
    'age'    => 35, 
    'children/0/name' => 'Meirav', 
    'children/0/age' => 6, 
    'children/1/name' => 'Maayan', 
    'children/1/age' => 4, 
    'dogs/0'   => 'Gili', 
    'dogs/1'   => 'Gipsy' 
); 

我開始寫一個遞歸函數這對於陣列元件將遞歸和非陣列元件(INT,浮點數,布爾變量,和字符串)返回一個數組$return['path']$return['value']。這很快就馬虎! 有沒有更好的方式在PHP中做到這一點?我會假設可數組和對象不會被傳入數組,儘管任何處理這種可能性的解決方案都是最好的。另外,我假定輸入數組在元素名稱中不會有/字符,但考慮到這可能是謹慎的! 請注意,輸入數組可以嵌套深達8層或更深層!

+0

遞歸函數最適合您的方案。 – kcsoft

回答

3

遞歸是真的,你就可以處理這個問題的唯一辦法,但這裏有一個簡單的版本入手:

function nested_values($array, $path=""){ 
    $output = array(); 
    foreach($array as $key => $value) { 
     if(is_array($value)) { 
      $output = array_merge($output, nested_values($value, (!empty($path)) ? $path.$key."/" : $key."/")); 
     } 
     else $output[$path.$key] = $value; 
    } 
    return $output; 
} 
+0

謝謝雅各布,這是一個了不起的例子! – dotancohen

+0

雅各布,我已經在[PHP公用程序函數](https://github.com/dotancohen/utility-functions)的github存儲庫中使用過您的代碼。你當然被列爲作者之一。特定的功能還沒有完成(這是它的一小塊),但我儘管你想知道。 – dotancohen

+0

謝謝你的信用。希望能幫助到你。 –

1
function getRecursive($path, $node) { 
    if (is_array($node)) { 
     $ret = ''; 
     foreach($node as $key => $val) 
      $ret .= getRecursive($path.'.'.$key, $val); 
     return $ret; 
    } 
    return $path.' => '.$node."\n"; 
} 
$r = getRecursive('', $someVar); 
print_r($r); 

所有你把它放在一個數組中。

+0

謝謝,這是一個翔實的答案。 – dotancohen