I have below array, which includes a set of default indexes, that must be present in my final array:
'entities' => [
'deliveredAt',
'issuedAt',
'totals' => [
'due',
'gross',
'net',
'tax' => [
'amount',
'net',
'rate',
],
]
],
The above array is saved in a variable called $entities
.
Now, I have a 3rd party API, that will return the above entities, but only include them in the response if the entity contains a value.
For example, a $response
can look like this:
array:2 [▼
"issuedAt" => "2020-08-20"
"totals" => array:1 [▼
"tax" => []
]
]
As you can see, if comparing the returned array with the indexes that I expect, there is a few missing:
deliveredAt
totals.due
,totals.gross
,totals.net
,totals.tax.amount
,totals.tax.net
,totals.tax.rate
I am trying to make a method that can iterate over the $response
array, and check if it contains the indexes that I expect. If not, I simply want to set the index with a value of null
.
Below is what I have so far:
foreach ($entities as $key => $entity) {
if (!is_array($entity)) {
if (!isset($response[$entity])) {
$response[$entity] = null;
}
}
}
However, this will only add an index that is not an array. In this example, it will only add: deliveredAt => null
.
How can I do, so the above method can iterate through multiple at least 2 nested arrays and add the index name and null
value?
Advertisement
Answer
You can define initial array with keys and NULL
(or whatever you need) as values:
$entities = [
'deliveredAt' => null,
'issuedAt' => null,
'totals' => [
'due' => null,
'gross' => null,
'net' => null,
'tax' => [
'amount' => null,
'net' => null,
'rate' => null,
],
]
];
// here's your real data
$realData = [
"issuedAt" => "2020-08-20",
"totals" => [
"tax" => [
'net' => 42,
]
]
];
// now use array_replace_recursive to replace keys in `$entities` with values of `$realData`
print_r(array_replace_recursive($entities, $realData));
Also note that keys from $realData
that do not exist in $entities
will be added to result.