From sql I create an array $sails that look like:
Array
(
[0] => Array
(
[type] => RES
[date] => 2022-05-14
[doy] => 133
[skipperid] => 217
[boat] => Laura
[start] => 09:00:00
[end] => 22:00:00
[spots] => 5
[fname] => David
[lname] => Cross
)
[1] => Array
(
[type] => SAIL
[date] => 2022-05-14
[doy] => 133
[skipperid] => 1
[boat] => Avrora
[start] => 10:00:00
[end] => 13:00:00
[spots] => 3
[fname] => Bob
[lname] => Smith
)
[2] => Array
(
[type] => RES
[date] => 2022-05-24
[doy] => 143
[skipperid] => 1
[boat] => Irlbach
[start] => 09:00:00
[end] => 13:30:00
[spots] => 3
[fname] => Bob
[lname] => Smith
)
)
I want to convert this to an object of arrays of objects. Essentially something that looks like
{[{},{}],[{}]}
Here's what I am trying:
$allSails = new stdClass();
$sailCnt = count($sails);
for($i = 0; $i < $sailCnt; $i++){
$dayKey = $sails[$i]['doy'];
$allSails->$dayKey = array();
$itmCnt = count($sails[$i]);
$keys = array_keys($sails[$i]);
$items = new stdClass();
$j = 0;
foreach($keys as $key){
$items->$key = $sails[$i][$keys[$j]];
$j++;
}
array_push($allSails->$dayKey, clone $items);
}
but this is the output:
stdClass Object
(
[133] => Array
(
[0] => stdClass Object
(
[type] => SAIL
[date] => 2022-05-14
[doy] => 133
[skipperid] => 1
[boat] => Avrora
[start] => 10:00:00
[end] => 13:00:00
[spots] => 3
[fname] => Bob
[lname] => Smith
)
)
[143] => Array
(
[0] => stdClass Object
(
[type] => RES
[date] => 2022-05-24
[doy] => 143
[skipperid] => 1
[boat] => Irlbach
[start] => 09:00:00
[end] => 13:30:00
[spots] => 3
[fname] => Bob
[lname] => Smith
)
)
)
$items = (object) $sails[$i];foreach($sails[$i] as $sail) {...}, and if you need the key doforeach($sails[$i] as $key => $sail) {...}array_pushbut this portion of code:$allSails->$dayKey = array();. It was always setting the key to an empty array and you need to do it just once (like in the various solutions given, first check if it doesn't exist, create the empty array, if it already exist just add more elements to it).