I've got a multidimensionnal array :
[
1 => [
'name' => 'EC567'
'type' => 'B3000'
'value' => '4DFYU'
],
2 => [
'name' => '1C527'
'type' => 'B3UI0'
'value' => '4DMNU'
]
]
And a single array which is my model :
['EC567', 'RD678','9O0PM','1C527']
I need to sort the multidimensionnal array by name from the single array which contains the list of all the names.
Any idea ?
CodePudding user response:
You can use a custom sort function usort()
, and use array_search()
to order it using spaceship operator <=>
.
Code (demo):
$arr = [
1 => [
'name' => 'EC567',
'type' => 'B3000',
'value' => '4DFYU',
],
2 => [
'name' => '1C527',
'type' => 'B3UI0',
'value' => '4DMNU',
]
];
$order = ['RD678', '9O0PM', '1C527', 'EC567'];
usort($arr, fn(array $a, array $b): int =>
array_search($a['name'], $order) <=> array_search($b['name'], $order)
);
Output:
array(2) {
[0]=>
array(3) {
["name"]=> string(5) "1C527"
["type"]=> string(5) "B3UI0"
["value"]=> string(5) "4DMNU"
}
[1]=>
array(3) {
["name"]=> string(5) "EC567"
["type"]=> string(5) "B3000"
["value"]=> string(5) "4DFYU"
}
}
For PHP version lower than 7.4,
usort($arr, function(array $a, array $b) use($order): int {
return array_search($a['name'], $order) <=> array_search($b['name'], $order);
});
CodePudding user response:
$multiArray = [
1 => [
'name' => 'EC567',
'type' => 'B3000',
'value' => '4DFYU'
],
2 => [
'name' => '1C527',
'type' => 'B3UI0',
'value' => '4DMNU'
]
];
$singleArray = ['EC567', 'RD678','9O0PM', '1C527'];
$sortedArray = [];
for ($i=0; $i < count($singleArray); $i ) {
foreach ($multiArray as $key => $value) {
if ($multiArray[$key]["name"] == $singleArray[$i]) {
array_push($sortedArray, $multiArray[$key]);
}
}
}
print_r($sortedArray);
Output:
[0] => Array
(
[name] => EC567
[type] => B3000
[value] => 4DFYU
)
[1] => Array
(
[name] => 1C527
[type] => B3UI0
[value] => 4DMNU
)
CodePudding user response:
$list = [
[ 'name' => 'EC567', 'type' => 'B3000', 'value' => '4DFYU' ],
[ 'name' => '1C527', 'type' => 'B3UI0', 'value' => '4DMNU' ],
[ 'name' => '9O0PM', 'type' => 'B3ZZZ', 'value' => '4DNNN' ]
];
$sortOrder = [ 'EC567', 'RD678', '9O0PM', '1C527' ];
$result = [];
array_walk($sortOrder, function ($value, $key) use ($list, &$result) {
$items = array_filter($list, fn($item) => $item['name'] === $value);
if (count($items)) {
$result = array_merge($result, $items);
}
});
print_r($result);
Output:
Array
(
[0] => Array
(
[name] => EC567
[type] => B3000
[value] => 4DFYU
)
[1] => Array
(
[name] => 9O0PM
[type] => B3ZZZ
[value] => 4DNNN
)
[2] => Array
(
[name] => 1C527
[type] => B3UI0
[value] => 4DMNU
)
)