【问题标题】:PHP foreach is not looping through JSON filePHP foreach 没有循环遍历 JSON 文件
【发布时间】:2019-12-08 19:37:05
【问题描述】:

foreach 函数未在此 JSON 文件上运行。

我希望 PHP 循环遍历 JSON 文件并以 HTML 表格格式输出数据。

<?php
// Store JSON data in a PHP variable
$url = 'https://eztv.io/api/get-torrents?limit=100&page=1'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
//var_dump(json_decode($data));
$shows = json_decode($data, true); // decode the JSON feed and make an associative array
?>
<br /><br /><br /><br />

<table>
<?php
foreach ($shows as $shows) : ?>
    <tr>
        <td> <strong><?php echo $shows["title"] . "\n"; ?></strong>  </td>
        <td> <strong><?php echo $shows["season"] . "\n"; ?></strong>  </td>
        <td> <strong><?php echo $shows["episode"] . "\n"; ?></strong>  </td>
        <td> <a href="<?php echo $shows["magnet_url"] . "\n"; ?>">magnet</a></td>
        <td> <?php echo $shows["date_released_unix"] . "\n"; ?>  </td>
        <td> <?php echo $shows["size_bytes"] . "\n"; ?>  </td>
        <td> <a href="<?php echo $shows["episode_url"] . "\n"; ?>">episode Link</a></td>
        <td> <?php echo $shows["imdb_id"] . "\n"; ?>  </td>
    </tr>
<?php endforeach; ?>
</table>

如果我运行此代码,我会在页面上收到 Notice: Undefined index: 错误。

【问题讨论】:

  • 不知道json字符串是怎样的
  • json 的链接是eztv.io/api/get-torrents?limit=100&page=1 还是我应该把它贴在这里?
  • 不要使用链接,发布 json 文件(如果它很大,我们需要阅读以帮助您的部分)

标签: php json loops foreach


【解决方案1】:

torrents 响应键处的所有数据。 您应该检查数组索引/键是否存在。

<?php 
$url = 'https://eztv.io/api/get-torrents?limit=100&page=1'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$shows = json_decode($data, true); // decode the JSON feed and make an associative array 
<?php foreach ($shows['torrents'] as $shows) : ?>
    <tr></tr>
<?php endforeach; ?>

【讨论】:

    【解决方案2】:
    foreach ($shows as $shows) : ?>
        <tr>
            <td> <strong><?php echo $shows["title"] ?? '' . "\n"; ?></strong>  </td>
            <td> <strong><?php echo $shows["season"] ?? '' . "\n"; ?></strong>  </td>
            <td> <strong><?php echo $shows["episode"] ?? '' . "\n"; ?></strong>  </td>
            <td> <a href="<?php echo $shows["magnet_url"] ?? '' . "\n"; ?>">magnet</a></td>
            <td> <?php echo $shows["date_released_unix"] ?? '' . "\n"; ?>  </td>
            <td> <?php echo $shows["size_bytes"] ?? '' . "\n"; ?>  </td>
            <td> <a href="<?php echo $shows["episode_url"] ?? '' . "\n"; ?>">episode Link</a></td>
            <td> <?php echo $shows["imdb_id"] ?? '' . "\n"; ?>  </td>
        </tr>
    <?php endforeach; ?>
    

    类似于 Shivendra Singh 的回答,但我们使用空聚结剂只是为了让事情更容易阅读。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 2011-06-11
      • 2013-02-06
      相关资源
      最近更新 更多