简体   繁体   English

打印嵌套的 JSON 字典

[英]Printing nested JSON dictionary

I have an API and I have problem accessing the contents using PHP.我有一个 API,但在使用 PHP 访问内容时遇到问题。

Below is the API structure:下面是API结构:

"data": {
  "1076056102": {
    "achievements": {
        "armorPiercer": 25,
        "rare1070": 1,
        "aimer": 4,
        "invader": 12,
        ...//

Below is the code I have to try and access it.下面是我必须尝试访问它的代码。 Any help would be nice thank you.任何帮助都会很好谢谢。

$url = '...'; JSON PATH
$data = file_get_contents($url); // put contents in variable
$stats = json_decode($data); // decode the JSON feed
?>

<html>
<table>
<tbody>
    <tr>
        <th>Achievement</th>
    </tr>
    <?php foreach ($stats as $stat) : ?>
    <tr>
        <td> <?php echo $stat->armorPiercer; ?> </td>
        <td> <?php echo $stat->rare1070; ?> </td>
        <td> <?php echo $stat->aimer; ?> </td>
        <td> <?php echo $stat->invader; ?> </td>
    </tr>
    <?php endforeach; ?>
</tbody>
</table>
echo $object->data->{1076056102}->achievements->armorPiercer;

will work.将工作。 However, I'm guessing you won't know those ID's specifically.但是,我猜您不会特别知道这些 ID。

So, turn it into an associative array rather than a stdClass by passing true to json_decode() :因此,通过将 true 传递给json_decode()将其转换为关联数组而不是stdClass

$array = json_decode($json, true);
foreach ($array['data'] as $row) {
    echo $row['achievements']['armorPiercer']; // echoes 25
}

Check it out here https://3v4l.org/4W3mm在这里查看https://3v4l.org/4W3mm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM