I have an array of objects that I'm converting to a CSV file for export. My problem is, that the objects are not identical in terms of keys. Some contain more than others.
My array of objects could look like this:
Array
(
[0] => stdClass Object
(
[Type] => Company
[Address] => My Address
[Zip] => 1234
[City] => Cityname
)
[1] => stdClass Object
(
[Type] => Private
[Status] => Inactive
)
)
How can I convert an array of objects so each object would contain all possible "keys" even though they are empty, e.g. like this for the above example:
Array
(
[0] => stdClass Object
(
[Type] => Company
[Address] => My Address
[Zip] => 1234
[City] => Cityname
[Status] =>
)
[1] => stdClass Object
(
[Type] => Private
[Address] =>
[Zip] =>
[City] =>
[Status] => Inactive
)
)
I think I would have to get all keys first and then some sort of mapping into them for each object. My hope is, there's some clever way to do this, but I'm totally lost here.
Edit
I have collected all my keys in a $headers array and mapped all data to the new array of objects. Not sure if this is the most elegant way, but it works.
$records = json_decode($records);
$headers = array();
foreach ($records as $object) {
foreach ($object as $key => $value) {
$headers[] = $key;
}
}
$headers = array_unique($headers);
$export = array();
$i = 0;
foreach ($records as $object) {
$newObject = new stdClass();
foreach ($headers as $key) {
$newObject->$key = $object->$key;
}
$export[$i] = $newObject;
$i++;
}