簡體   English   中英

打印嵌套的 JSON 字典

[英]Printing nested JSON dictionary

我有一個 API,但在使用 PHP 訪問內容時遇到問題。

下面是API結構:

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

下面是我必須嘗試訪問它的代碼。 任何幫助都會很好謝謝。

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

將工作。 但是,我猜您不會特別知道這些 ID。

因此,通過將 true 傳遞給json_decode()將其轉換為關聯數組而不是stdClass

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

在這里查看https://3v4l.org/4W3mm

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM