【问题标题】:How to dynamically repeat for all children of a JSON array, that may have children (PHP)如何为可能有孩子的JSON数组的所有孩子动态重复(PHP)
【发布时间】:2020-04-24 14:36:35
【问题描述】:

我正在尝试编写一个网站,该网站获取 Reddit 页面的 cmets 并显示它们。但是,cmets 有回复,我也想显示这些回复,但是评论可以没有回复,一个或多个回复,并且这些回复可以有回复。有没有办法为所有有微小差异(缩进)的回复重复相同的代码?我正在使用 reddit json 功能,并且正在从类似这里的地方获取 JSON:https://www.reddit.com/r/pcmasterrace/comments/dln0o3/foldinghome_and_pcmr_team_up_use_your_pc_to_help/.json。 我有:

$url = ('https://www.reddit.com/r/pcmasterrace/comments/dln0o3/foldinghome_and_pcmr_team_up_use_your_pc_to_help/.json');
$json = file_get_contents($url);
$obj = json_decode($json, true);

$comment_array = array_slice($obj[1]['data']['children'], 0, 50);
echo '<div class="comments">';
foreach ($comment_array as $c) {
    echo "<p>(".$c['data']['author'].") ". $c['data']['score'] . " Points<br>".$c['data']['body']."</p>";
    if (!($c['data']['replies'] == "")) {
        $r1_array = $c['data']['replies']['data']['children'];
        foreach ($r1_array as $r1) {
            echo "<p>    (".$r1['data']['author'].") ". $r1['data']['score'] . " Points<br>    ".$r1['data']['body']."</p>";
            if (!($r1['data']['replies'] == "")) {
                $r2_array = $r1['data']['replies']['data']['children'];
                foreach ($r2_array as $r2) {
                    echo "<p>        (".$r2['data']['author'].") ". $r1['data']['score'] . " Points<br>        ".$r2['data']['body']."</p>";
                }
            }
        }
    }
}
}

这会产生所需的结果,包括对回复的回复等。不过有点乱,如果回复链真的很长,就抓不住了。有没有办法让它以某种方式重复,或者我应该复制并粘贴很多次? 非常感谢!

【问题讨论】:

  • 好吧,看,让我们精简一下,试着让你的问题清晰、最小化和可验证。删除 sn-p 中的前三行 - 因为您在接收文件内容时没有任何问题。 (当它实际上是一个数组时,我们不要将您的输入称为$obj)向我们展示一个足够大的样本输入($array)——它需要有足够的回复以及任何使数据真实的东西,但我们没有想要一个包含 1000 个元素的数组。您已经向我们展示了您的代码,这很棒。最后向我们展示您当前的输出并向我们展示您想要的输出。请编辑您的问题。

标签: php recursion multidimensional-array


【解决方案1】:

我认为您正在寻找一个名为 recursion 的概念。

基本思想是函数将根据需要多次调用自身(而不是使用固定数量的循环)。

类似这样的:

<?php

function output($data, $level = 0) {
  $spaces = str_repeat(' &nbsp;', $level);
  foreach ($data as $post) {
    echo "<p>(".$spaces.$post['data']['author'].") ". $post['data']['score'] . " Points<br>".$post['data']['body']."</p>\r\n";
    if ($post['data']['replies']) {

      // Notice that we are calling the function again, this time increasing the level
      // This is the "recursive" part of the function
      output($post['data']['replies']['data']['children'], $level + 1);

    }
  }
}

$url = ('https://www.reddit.com/r/pcmasterrace/comments/dln0o3/foldinghome_and_pcmr_team_up_use_your_pc_to_help/.json');
$json = file_get_contents($url);
$data = json_decode($json, true);
$comment_array = array_slice($data[1]['data']['children'], 0, 50);
output($comment_array);

?>

【讨论】:

    猜你喜欢
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 2014-03-27
    • 2013-07-30
    • 1970-01-01
    相关资源
    最近更新 更多