在foreach循环后比较JSON

时间:2016-06-20 19:19:23

标签: php json foreach

我有一个JSON文件here

我希望<li></li>循环遍历所有频道,获取其ID,然后将其与在给定频道数组中拥有channel_id的会员进行比较,但我不确定如何正确完成此操作。

我们的想法是在渠道名称下的$discord = json_decode(file_get_contents('https://discordapp.com/api/servers/'.$id.'/widget.json')); if ($discord->channels) { usort($discord->channels, function($a, $b) { return $a->position > $b->position ? 1 : -1; }); echo '<ul>'; foreach ($discord->channels as $channel) { echo "<li>{$channel->name}</li>"; } echo '</ul>'; } 中有一个当前位于频道中的用户列表。

foreach ($discord->members as $member)

我的代码是否正确。显然我需要做另一个$member->channel_id,然后检查<ul> <li>Channel 1 <ul> <li>User 1</li> <li>User 2</li> </ul> </li> <li>Channel 2</li> <li>Channel 3 <ul> <li>User 3</li> </ul> </li> </ul> 但是什么是一个简单的方法来正确输出?

最后,我想要的是:

.\SQLEXPRESS

因此,频道1中有2个用户,频道2中没有用户,频道3中有1个用户。

希望这是有道理的。提前谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

$discord = json_decode(file_get_contents('https://discordapp.com/api/servers/'.$id.'/widget.json'));
  if ($discord->channels) {
    usort($discord->channels, function($a, $b) {
      return $a->position > $b->position ? 1 : -1;
    });

    echo '<ul>';

    foreach ($discord->members as $member) {
        if (!empty($member->channel_id)) {
            $channel_members[$member->channel_id][] = $member->username;
        }
    }

    foreach ($discord->channels as $channel) {
      echo "<li>{$channel->name}";
      if (!empty($channel_members[$channel->id])) {
            echo '<ul>';
            foreach ($channel_members[$channel->id] as $username) {
              echo "<li>$username</li>";
            }
            echo '</ul>';
      }
      echo "</li>";
    }

    echo '</ul>';
  }