I have two arrays. They look like these:
$array1 = [
[
"filename" => "test1.pptx",
"article" => "article",
"category 1" => "cat1",
"category 2" => "cat2",
"category 3" => "cat3",
]
];
$array2 = [
[
"filename" => "test1.pptx",
"date" => "2023-08-29 11:05:59"
],
[
"filename" => "test1.pptx",
"date" => "2024-01-29 12:05:59"
],
"filename" => "test1.pptx",
"date" => "2023-06-30 12:05:59"
]
];
The count of $array2 is approx. 300 and the count of $array1 is 40.
Both arrays have the key “filename” and it will match a lot of times. Each time it matches I want the values of the matched $array2 array and $array1 array stored in a new array.
“filename” should exist once in the new array.
So for this example it should to look like this:
$mergedFileOutputs = [
[
"filename" => "test1.pptx",
"article" => "article",
"category 1" => "cat1",
"category 2" => "cat2",
"category 3" => "cat3",
"date" => "2023-08-29 11:05:59"
],
[
"filename" => "test1.pptx",
"article" => "article",
"category 1" => "cat1",
"category 2" => "cat2",
"category 3" => "cat3",
"date" => "2024-01-29 12:05:59"
],
[
"filename" => "test1.pptx",
"article" => "article",
"category 1" => "cat1",
"category 2" => "cat2",
"category 3" => "cat3",
"date" => "2023-06-30 12:05:59"
],
];
I can’t seem to find a way to get an array with the amount of $array2 arrays just filled with the matched “filename” values of $array1.
Thanks in advance for any kind of help!
To achieve this I tried the following:
$mergedFileOutputs = [];
foreach ($array2 as $file2) {
foreach ($array1 as $file1) {
$filename = $file1['filename'];
if ($file2['filename'] === $filename) {
$mergedFileOutputs[] =
[
'filename' => $array1['filename'],
'article' => $array1['article'],
'category 1' => $array1['category 1'],
'category 2' => $array1['category 2'],
'category 3' => $array1['category 3'],
'date' => $array2['date'],
];
}
}
}
Now the problem is that I receive 40 arrays that are correctly filled, which is the amount of arrays that are $array1.
Since I have a lot more $array2s I need this amount of arrays. I tried several options with array_merge
and had the same results, so I posted this solution as it’s the most simple.
Ichigo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1