Using PHP, I have an array like this:
Array 1
[
{epid: "123", hash: "xxxxxx"},
{epid: "456", hash: "xxxxxx"},
{epid: "789", hash: "xxxxxx"},
{epid: "123", hash: "xxxxxx"},
{epid: "123", hash: "xxxxxx"},
]
Then, I have a second array like this:
Array 2
[
{epid: "123", name: "This is a title"},
{epid: "456", name: "This is a title"},
{epid: "789", name: "This is a title"}
]
My goal is to get all hash from array one and add them to the appropriate record in array 2. From this example, the results would be:
[
{epid: "123", name: "This is a title", hash: [ xxxxxx, xxxxxx, xxxxxx ] },
{epid: "456", name: "This is a title", hash: [ xxxxxx ] },
{epid: "789", name: "This is a title", hash: [ xxxxxx ] }
]
I'm sure there are multiple loops here, but for the life of me, I can't wrap my brain around it.
CodePudding user response:
You could loop through the second array and use the epid to find the indexes in the first array. Then for every index found, add the hash to the current loop item:
$lookup = [
["epid" => "123", "hash" => "xxxxxxA"],
["epid" => "456", "hash" => "xxxxxxB"],
["epid" => "789", "hash" => "xxxxxxC"],
["epid" => "123", "hash" => "xxxxxxD"],
["epid" => "123", "hash" => "xxxxxxE"],
];
$db = [
["epid" => "123", "name" => "This is a title"],
["epid" => "456", "name" => "This is a title"],
["epid" => "789", "name" => "This is a title"]
];
foreach($db as $i => $el) {
$keys = array_keys(array_column($lookup, 'epid'), $el["epid"]);
foreach($keys as $key) {
$db[$i]["hash"][] = $lookup[$key]["hash"];
}
}
var_dump($db);
CodePudding user response:
I assume you don't actually have a json array, but a php array. If not, you have to convert them before.
Iterate over each entry in array2
and filter the matching items out of the array1
. If done, you can easily get the hashes via array_column
and add them to array2
.
$array1 = [
['epid' => "123", 'hash' => "xxxxxx"],
['epid' => "456", 'hash' => "xxxxxx"],
['epid' => "789", 'hash' => "xxxxxx"],
['epid' => "123", 'hash' => "xxxxxx"],
['epid' => "123", 'hash' => "xxxxxx"],
];
$array2 = [
['epid' => "123", 'name' => "This is a title"],
['epid' => "456", 'name' => "This is a title"],
['epid' => "789", 'name' => "This is a title"]
];
foreach ($array2 as $key => $data) {
$matching = array_filter($array1, static fn($filterValue) => $data['epid'] === $filterValue['epid']);
$array2[$key]['hash'] = array_column($matching, 'hash');
}
Or, you could do it as short as possible with the following statement. It does exactly the same as the above, but is way more unreadable.
array_walk($array2, static fn(&$value) => $value['hash'] = array_column(array_filter($array1, static fn($filterValue) => $filterValue['epid'] === $value['epid']), 'hash'));