0

我必须提取一堆 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);

所以你可以看到我想要表达的意思。请任何帮助都会很棒!

4

1 回答 1

0

似乎您试图将 url 存储在一个数组中,这应该返回一个多维数组中的所有 url,其中 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;
}
于 2012-04-27T02:22:01.680 回答