2012-04-27 83 views
0

我必須拉一堆json文件,並從這些文件中的信息創建鏈接並遞歸到文件中。來自多個JSON文件的多級數組

{ 
    "_v" : "12.2", 
    "categories" : [ { 
    "id" : "boys-hats-and-beanies", 
    "name" : "Hats & Beanies" 
    } 
    ] 
} 

所以從這一點我需要建立另一個鏈接直接進入並獲得

http://xxx.xxx/?id=boys-hats-and=beanies.json

文件內容和文件中我可能會再次這樣做。正如我現在所知道的那樣,它將我需要的信息放入許多數組中,我希望它能保持層次結構。

$allLinks['root'] = array(); 
$allLinks['firstLevel'] = array(); 
$allLinks['secondLevel'] = array(); 
$allLinks['thirdLevel'] = array(); 

    function getContent($info){ 
     $content = file_get_contents($info); 
     return json_decode($content, true); 
    } 

    $new = getContent('https://xxx.xxx/?id=root'); 


    foreach ($new['categories'] as $name => $value) { 
      array_push($allLinks['root'], 'https://xxx.xxx/?id='.$value['id']); 
    } 

    foreach ($allLinks['root'] as $name => $value) { 
     $new = getContent($value); 
     foreach ($new['categories'] as $name => $value) { 
      array_push($allLinks['firstLevel'], 'https://xxx.xxx/?id='.$value['id']); 
     } 
    } 

    foreach ($allLinks['firstLevel'] as $name => $value) { 
     $new = getContent($value); 
     foreach ($new['categories'] as $name => $value) { 
      array_push($allLinks['secondLevel'], 'https://xxx.xxx/?id='.$value['id']); 
     } 
    } 

    foreach ($allLinks['secondLevel'] as $name => $value) { 
     $new = getContent($value); 
     foreach ($new['categories'] as $name => $value) { 
      array_push($allLinks['thirdLevel'], 'https://xxx.xxx/?id='.$value['id']); 
     } 
    } 


    print_r($allLinks); 

所以你可以看看我試圖得到什麼。請任何幫助將是偉大的!

回答

0

這似乎是你試圖存儲在一個數組中的網址,這應該返回一個多維數組中的所有網址,0是第一級。

function getContent($info){ 
    $content = file_get_contents($info); 
    return json_decode($content, true); 
} 

function getContentUrlById($id, $ext = '.json') 
{ 
    return 'https://xxx.xxx/?id=' . $id . $ext; 
} 

function getContentRecursive($id = 'root', $level = 0) 
{ 
    $result = array(); 
    $url = getContentUrlById($id); 
    $content = getContent($url); 
    $result[$level][] = $url; 
    foreach($content['categories'] as $cat){ 
     $result = array_merge_recursive($result, getContentRecursive($cat['id'], $level + 1)); 
    } 

    return $result; 
} 
+0

'$ return'應當'return' – deex 2012-04-27 02:24:41

+0

即給我這個 '陣列 ( [0] =>數組 ( [0] => https://xxx.xxx?id =根 ) [1] =>數組 ( [0] => https://xxx.xxx/?id=mens )' 等等.. – 2012-04-27 15:18:25