I have the following 2 arrays
$a = [
[
'name' => 'Fred',
'age' => 20,
'test' => 'sa'
],
[
'name' => 'Alex',
'age' => 18,
],
[
'name' => 'Anna',
'age' => 24,
],
[
'name' => 'Tommy',
'age' => 22
],
[
'name' => 'Amber',
'age' => 26
]
];
$b = [
['Fred'],
['Anna'],
['Alex'],
];
I want to be able to put the key values of the first array into the second array so that the sorting of the second array is the one to use. The expected output should look like the following:
$a = [
[
'name' => 'Fred',
'age' => 20,
'test' => 'sa'
],
[
'name' => 'Anna',
'age' => 24,
],
[
'name' => 'Alex',
'age' => 18,
],
];
I am not too sure how to achieve this using array_map or not sure if I am missing any other function to help me do that.
I have tried the following but still no luck.
I want to only be able to map the ones that have the same value of the key 'name'. Keeping in mind that array $a
is multidimensional and array $b
is multidimensional too but does not have a key 'name'.
$c = array_map('mapName', $a, $b);
function mapName($a, $b)
{
return $a['name'] == $b;
}
Would really appreciate if anyone can help. thanks.
CodePudding user response:
I think I'd just iterate the first array to create a mapping of the names, then iterate the second to lookup and order the results. Not sure it's the most efficient, but can't think how else to do it. Something like:
$keyMap = [];
foreach ($a as $idx => $aItem) {
$keyMap[$aItem['name']] = $idx;
}
$result = [];
foreach ($b as $bItem) {
// bItems are all arrays with one element
$foundItem = $a[$keyMap[$bItem[0]]] ?? null;
if (isset($foundItem)) {
$result[] = $foundItem;
}
}
I guess this could be shortened to:
$keyMap = array_flip(array_column($a, 'name'));
array_walk($b, function(&$v) use ($a, $keyMap) {
$v = $a[$keyMap[$v[0]]] ?? null;
});
Then $b has the result you're after.... I think
CodePudding user response:
Create a lookup, then map your array of names to the lookup data.
Code: (Demo)
$lookup = array_column($a, null, 'name');
var_export(
array_map(
fn($name) => $lookup[$name[0]],
$b
)
);
This snippet assumes the first array will always contain all values from the second array. If this is not always true, then you should update your sample data to represent this truth and explain how you wish to handle those cases.