Log1x Log1x - 5 months ago 17
JSON Question

Comparing JSON after foreach loop

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.

Answer

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