2016-07-29 41 views
1

我需要扁平化數組,同時確保沒有重複的鍵。平坦陣列,同時考慮到父鍵

例如讓我們說我有這樣的:

$arr = array(
    $foo = array(
     'donuts' => array(
       'name' => 'lionel ritchie', 
       'animal' => 'manatee', 
      ) 
    ) 
); 

我需要一個平面數組,看起來像這樣:

$arr = array(
    'donuts name' => 'lionel ritchie', 
    'donuts animal' => 'manatee', 
); 

它需要即使我們有超過1父項工作。

我有下面的代碼,但我不知道我可以用這個工作。

foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array1)) as $k=>$v){ 
    $array1c[$k] = $v; 
} 

回答

1
array_reduce($array, 'array_merge', array()) 

例如:

$a = array(array(1, 2, 3), array(4, 5, 6)); 
$result = array_reduce($a, 'array_merge', array()); 

結果:

array[1, 2, 3, 4, 5, 6]; 
1

這是很簡單的事,只要它是這樣的:

$arr = array(
    $foo = array(
     'donuts' => array(
       'name' => 'lionel ritchie', 
       'animal' => 'manatee', 
      ) 
    ) 
); 

// Will loop 'donuts' and other items that you can insert in the $foo array. 
foreach($foo as $findex => $child) { 
     // Remove item 'donuts' from array, it will get the numeric key of current element by using array_search and array_keys 
     array_splice($foo, array_search($findex, array_keys($foo)), 1); 
     foreach($child as $index => $value) { 
      // Adds an array element for every child 
      $foo[$findex.' '.$index] = $value; 
     } 
} 

var_dump($foo);結果將是:

array(2) { 
    ["donuts name"]=> 
    string(14) "lionel ritchie" 
    ["donuts animal"]=> 
    string(7) "manatee" 
} 

試試看:)

+0

它不應該是遞歸的關係嗎?假設我們有10位家長。 – dms

+0

是的,嘗試使這些操作遞歸的函數。 – Syncro