微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数组中的PHP foreach

如何解决数组中的PHP foreach

我正在使用一个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;

这里您要访问domainArray给定的数组上名为foreach()的属性。无需这样做,因为您已经在使用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>";
}

Try it online!


注意:使用null coalescing operator (?? [])确保数据中存在snapshotTimes


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

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

Try it online!

,

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

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.
    }
}

我强调指出,您需要check your PHP Error Log来帮助您诊断这类结构问题。

注意:

  • 您在foreach中的引用$arr->$domainArray->snapshotTimes不正确,您同时引用了foreach标签以及foreach标签的​​来源,这将导致错误。
  • PHP变量应以小写字母开头。
  • 如果由于其他原因在foreach循环中不需要$domainArray => $arr,则可以通过循环数组而不是 container 来简化循环,例如0stone0 shows on their answer

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。