Comparing JSON after foreach loop

半世苍凉 提交于 2020-01-07 00:06:53

问题


I have a JSON file here.

I would like to foreach loop through all of the channels, grab their ID, and then compare it to Members who have channel_id in their array of a given channel but am unsure how to accomplish this properly.

The idea is to have a list of users currently in the channels in a <li></li> under neath the channel name.

$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>';
  }

Is my code right now. Obviously I'd need to do another foreach ($discord->members as $member) and then check $member->channel_id but what is an easy way to get this to output properly?

In the end, I'd want something like:

<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>

So Channel 1 has 2 users in it, Channel 2 has no users in it, Channel 3 has 1 user in it.

Hope this makes sense. Thanks in advance.


回答1:


Try this:

$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>';
  }


来源:https://stackoverflow.com/questions/37930207/comparing-json-after-foreach-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!