phparraysforeach

Iterate an object containing a subarray


I am using an api to show a list of times but struggling to display them in using foreach

Here is how the data is shown:

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
        )

)

Code:

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

But it doesn't seem to echo anything at all? Where am I going wrong?


Solution

  • Your code shows;

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

    Here you're tying to access a property called domainArray on the array given by the foreach(). No need to do that since your already using the foreach() to loop over the data;

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


    Note: Using the null coalescing operator (?? []) to ensure snapshotTimes exists in the data.


    Based on comments; the same solution but with array_reverse() to reverse the output.

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

    Try it online!