2013-03-16 170 views
4

我有一個快速查詢有關如何將多維數組轉換成一維數組如何在PHP中將多維關聯數組轉換爲單維數組?

$teachers=array(array('post_id' => "John Doe",'video_id' => array('Government','English')), array('post_id' => "Steven Lee",'video_id' => array("Math","Science", "PE")),array('post_id' => "Jean Perot", 'video_id' => array("French", "Literature"))); 
+0

http://stackoverflow.com/questions/8611313/turning-multidimensional -array-into-one-dimensional-array – Wyck 2013-03-16 06:10:15

回答

0

試試這個

function array_values_recursive($ary) { 
    $lst = array(); 
    foreach(array_keys($ary) as $k) { 
     $v = $ary[$k]; 
     if (is_scalar($v)) { 
      $lst[] = $v; 
     } elseif (is_array($v)) { 
      $lst = array_merge($lst,array_values_recursive($v)); 
     } 
    } 
    return array_values(array_unique($lst)); // used array_value function for rekey 
} 

$teachers=array(
    array('post_id' => "John Doe",'video_id' => array('Government','English')), 
    array('post_id' => "Steven Lee",'video_id' => array("Math","Science", "PE")), 
    array('post_id' => "Jean Perot", 'video_id' => array("French", "Literature"))); 

$flat = array_values_recursive($teachers); 
print_r($flat); // OUTPUT : Array ([0] => John Doe [1] => Government [2] => English [3] => Steven Lee [4] => Math [5] => Science [6] => PE [7] => Jean Perot [8] => French [9] => Literature) 
+0

謝謝你....我真的很感謝你的快速soln ...它是我們想要的完美soln。 – dhairya 2013-03-18 04:41:03