I have an array of arrays and I want to loop through them and create another array. The inner arrays of original array has a property called 'type' and its value is 'invoice'. It can have multiple arrays of type = invoice. I want to populate a new array with this invoice type.
For example:
$originalArray = [
[
"type" => "note",
"format" => 'IMAGE'
],
[
"type" => "invoice",
"text" => "boom boom"
],
[
"type" => "invoice",
"text" => "bam bam"
]
];
$newArray = [];
So in the loop I want to first check if type is invoice. Then check if newArray has any with type invoice. If it doesn't then it will push this to newArray:
[
"type" => "invoice",
"values" => [
[
"type" => "text",
"text" => "boom boom",
],
]
]
if it does exist, then it will just push it to values array:
"values" => [
[
"type" => "text",
"text" => "boom boom",
],
[
"type" => "text",
"text" => "bam bam",
],
]
the final newArray should look like this:
[
"type" => "invoice",
"values" => [
[
"type" => "text",
"text" => "boom boom",
],
[
"type" => "text",
"text" => "bam bam",
],
]
]
This is what I tried so far:
$originalArray = [
[
"type" => "note",
"format" => 'IMAGE'
],
[
"type" => "invoice",
"text" => "boom boom"
],
[
"type" => "invoice",
"text" => "bam bam"
]
];
$newArray = [];
foreach ($originalArray as $arr) {
if ($arr['type'] === 'invoice') {
if (in_array("invoice", array_column($newArray, "type"))) {
foreach ($newArray as $item) {
if ($item['type'] === 'invoice') {
$item['values'][] = [
'type' => 'text',
'text' => $arr['text']
];
}
}
} else {
$newArray[] = [
'type' => 'invoice',
'values' => [
[
'type' => 'text',
'text' => $arr['text'],
],
],
];
}
}
}
var_dump($newArray);
The dump only shows one invoice item, the first one. What am I doing wrong here?