2015-12-30 92 views
-1

我想這個數組轉換在一維平面數組不失排序順序。該陣列格式轉換爲單一陣列在PHP

 
Array 
(
    [0] => Array 
     (
      [id] => 1 
      [title] => Computer 
      [parent_id] => 0 
      [children] => Array 
       (
        [0] => Array 
         (
          [id] => 4 
          [title] => keyboard 
          [parent_id] => 1 
          [children] => Array 
           (
            [0] => Array 
             (
              [id] => 6 
              [title] => Mouse 
              [parent_id] => 4 
              [children] => Array 
               (
                [0] => Array 
                 (
                  [id] => 7 
                  [title] => webcam 
                  [parent_id] => 6 
                 ) 

               ) 

             ) 

           ) 

         ) 

       ) 

     ) 

    [1] => Array 
     (
      [id] => 43 
      [title] => Mobile 
      [parent_id] => 0 
      [children] => Array 
       (
        [0] => Array 
         (
          [id] => 5 
          [title] => bar phones 
          [parent_id] => 43 
         ) 

        [1] => Array 
         (
          [id] => 47 
          [title] => Touchscreen 
          [parent_id] => 43 
          [children] => Array 
           (
            [0] => Array 
             (
              [id] => 41 
              [title] => Samsung 
              [parent_id] => 47 
             ) 

            [1] => Array 
             (
              [id] => 44 
              [title] => Micromax 
              [parent_id] => 47 
             ) 

            [2] => Array 
             (
              [id] => 45 
              [title] => Huawei 
              [parent_id] => 47 
             ) 

           ) 

         ) 

       ) 

     ) 

    [2] => Array 
     (
      [id] => 46 
      [title] => Camera 
      [parent_id] => 0 
     ) 

    [3] => Array 
     (
      [id] => 42 
      [title] => Heater 
      [parent_id] => 0 
     ) 

) 
+0

編寫推每個元素到結果陣列的遞歸函數。 – Barmar

+0

你想把孩子和父母結合在一起? – devpro

+4

的可能的複製[如何拼合多維數組?](http://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array) –

回答

0

給它下面功能嘗試:

function makeOneDimensionArray(array $array, &$res = array()) 
{ 
    foreach($array as $arr) 
    { 
     $res[] = array(
      'id' => $arr['id'], 
      'title' => $arr['title'], 
      'parent_id' => $arr['parent_id'] 
     ); 
     if(isset($arr['children'])) 
     { 
      makeOneDimensionArray($arr['children'], $res); 
     } 
    } 
    return $res; 
} 

$finalArr = makeOneDimensionArray($your_array); 
print_r($finalArr); 
+0

謝謝巴迪:)工程就像一個魅力:) –

+0

很高興幫助:) –