繁体   English   中英

来自数组的 PHP foreach

[英]PHP foreach from array

我正在使用 api 来显示时间列表,但在使用foreach很难显示它们

以下是数据的显示方式:

stdClass Object
(
    [id] => 2507525
    [snapshotTimes] => Array
        (
            [0] => 2020-10-02T04:04:41+00:00
            [1] => 2020-10-03T03:22:29+00:00
            [2] => 2020-10-04T03:06:43+00:00
            [3] => 2020-10-04T21:18:11+00:00
            [4] => 2020-10-06T03:07:12+00:00
            [5] => 2020-10-07T03:21:31+00:00
            [6] => 2020-10-10T03:43:00+00:00
            [7] => 2020-10-17T02:58:49+00:00
            [8] => 2020-10-19T02:57:35+00:00
            [9] => 2020-10-23T03:08:28+00:00
            [10] => 2020-10-26T04:02:51+00:00
            [11] => 2020-10-27T04:33:19+00:00
        )

)

代码:

$domainArray = $services_api->getWithFields("/package/2507525/web/timelineBackup/web");
foreach ($domainArray as $arr) {
    $Time = $arr->$domainArray->snapshotTimes;
    echo " TIME: $Time<br>";
}

但它似乎根本没有回声? 我哪里错了?

您的代码显示;

$Time = $arr->$domainArray->snapshotTimes;

在这里,您要访问由foreach()给出的数组上名为domainArray的属性。 无需这样做,因为您已经使用foreach()来循环数据;

$domainArray = $services_api->getWithFields("/package/2507525/web/timelineBackup/web");

// For each item in the 'snapshotTimes' array
foreach ($domainArray->snapshotTimes ?? [] as $time) {
    echo " TIME: {$time}<br>";
}

在线试试吧!


注意:使用空合并运算符 ( ?? [] )确保数据中存在snapshotTimes


基于评论; 相同的解决方案,但使用array_reverse()来反转输出。

foreach (array_reverse($domainArray->snapshotTimes) as $time) {
    ....

在线试试吧!

您正在尝试打印快照时间,但您为另一件事创建了一个循环。 如果要打印 snapshotTimes 代码将如下所示:

foreach($arr->$domainArray->snapshotTimes as $time){
    echo $time."</br>";
}

snapshotTimes是一个数组,但您将其视为字符串。 您可能应该运行另一个内部 foreach 来循环遍历snapshotTimes所有值。 检查您的 PHP 错误日志。

也许一个例子会帮助他@Martin?

例子:

$domainArray = $services_api->getWithFields("/package/2507525/web/timelineBackup/web");
foreach ($domainArray as $arr) {
   if(is_array($arr->snapshotTimes) && count($arr->snapshotTimes) > 0 ){
    $times = $arr->snapshotTimes;
    foreach($times as $timeRow){
        echo " TIME: ".$timeRow."<br>";
    }
    unset($times); //tidy up temp vars.
    }
}

我强调您需要检查 PHP 错误日志以帮助您诊断此类结构问题。

笔记:

  • 您在 foreach 中的引用$arr->$domainArray->snapshotTimes不正确,您同时引用了 foreach 标签以及 foreach 标签的来源,这将导致错误。
  • PHP 变量应以小写字母开头。
  • 如果您不需要$domainArray => $arr在 foreach 循环中的任何其他原因,您可以通过循环数组而不是容器来简化循环,如0stone0 在他们的答案中所示

暂无
暂无

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

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