2016-09-02 54 views
1

我是一名新手PHP程序員。我今天遇到了一個問題。這裏的東西。如何讀取有大量嵌套實體的數組

我有這樣

$array = array("id" => 1, 
       "region"=>"world", 
       "parentid" => 0, 
       "children" => array("id" => 39, 
            "region"=>"asia", 
            "parentid" => 1, 
            "children" => array("id" => 70, 
                 "region"=>"china", 
                 "parentid" => 39 
                 ) 
           ) 
      ); 

我想這樣structrue一些結果的數組。

world 
    |- asia 
    |----- china 

這是我的代碼,它看起來非常糟糕,即使它工作。但它不會很好地工作時的水平超過3

$array = array(); 
$count = 0; 
for ($i = 0; $i < count($dep); $i++) { 
$array[]["region"] = $dep[$i]["region"]; 
if (isset($dep[$i]["children"])) { 
    for ($ii = 0; $ii < count($dep[$i]["children"]); $ii++) { 
     $array[]["region"] = $dep[$i]["children"][$ii]["region"]; 
     if (isset($dep[$i]["children"][$ii]["children"])) { 
      for ($iii = 0; $iii < count($dep[$i]["children"][$ii]["children"]); $iii++) { 
       $array[]["region"] = $dep[$i]["children"][$ii]["children"][$iii]["region"]; 
      } 
     } 
    } 
} 
} 

return $array; 

一定有更好的解決辦法來解決這個問題。任何幫助將不勝感激。

+2

你可能想寫一個遞歸函數。 – Rizier123

+0

你必須寫一個遞歸函數。 – Manish

+0

看看一些鏈接,會給你一些想法如何編寫遞歸函數 [https://www.copterlabs.com/build-menu-with-recursive-functions/] [http://lornajane.net/posts/2012/php-recursive-function-example-factorial-numbers] – Manish

回答

0

你應該利用遞歸。這意味着一個自稱的功能。讓我粘貼一個函數:

$array = [ 
    [ 
    "region" => "world", 
    "children" => [ 
     [ 
     "region"=> "asia", 
     "children" => [ 
      [ "region"=> "china" ], 
     ] 
     ], 
     [ 
     "region"=> "europe", 
     "children" => [ 
      [ "region"=>"czech republic" ], 
     ] 
     ] 
    ] 
    ] 
]; 


function format($dataset, $prefix = '') 
{ 
    foreach ($dataset as $data) { 
    echo $prefix . ' ' . $data['region'] . '<br>'; 

    if (! isset($data['children'])) { 
     return; 
    } 

    format($data['children'], $prefix . '--'); 
    } 
} 

format($array); 

你必須改變數組的結構,但功能更簡單。此外,idparent鍵變得多餘。

+0

謝謝我嘗試了代碼,但它不會很好。它回聲如下: 世界 - 其他地區消失。 – Bluestone