我正在使用 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>";
}
注意: 使用 null 合并运算符 (
?? []
) 确保数据中存在 snapshotTimes
。
array_reverse()
来反转输出。
foreach (array_reverse($domainArray->snapshotTimes) as $time) {
....
您正在尝试打印 snapshotTimes,但您为另一件事创建了循环。如果你想打印 snapshotTimes 代码将是这样的:
foreach($arr->$domainArray->snapshotTimes as $time){
echo $time."</br>";
}
是一个数组,但您将它视为一个字符串。您可能应该运行另一个内部 foreach 来循环snapshotTimes
中的所有值。检查您的 PHP 错误日志。snapshotTimes
也许一个例子可以帮助他@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 错误日志以帮助您诊断此类结构问题。
$arr->$domainArray->snapshotTimes
不正确,您引用了 foreach 标签以及 foreach 标签的源,这将导致错误。$domainArray => $arr
,您可以通过循环数组而不是 container 来简化循环,如 0stone0 在他们的答案中显示。