I would like to Sort an Array with its sub array value ("Name") but keeping its original array key.
default Array:
Array (
[251] => Array
(
[color] =>
[name] => 8
[nbr] => 1
[url_name] => taille-8
[meta_title] =>
)
[323] => Array
(
[color] =>
[name] => 7
[nbr] => 2
[url_name] => taille-7
[meta_title] =>
)
[127] => Array
(
[color] =>
[name] => 34
[nbr] => 2
[url_name] => taille-34
[meta_title] =>
)
);
By using array_multisort, I can able to get following Array:
Array(
[0] => Array
(
[color] =>
[name] => 7
[nbr] => 2
[url_name] => taille-7
[meta_title] =>
)
[1] => Array
(
[color] =>
[name] => 8
[nbr] => 1
[url_name] => taille-8
[meta_title] =>
)
[2] => Array
(
[color] =>
[name] => 34
[nbr] => 2
[url_name] => taille-34
[meta_title] =>
)
);
But what i need is,
Array(
[323] => Array
(
[color] =>
[name] => 7
[nbr] => 2
[url_name] => taille-7
[meta_title] =>
)
[251] => Array
(
[color] =>
[name] => 8
[nbr] => 1
[url_name] => taille-8
[meta_title] =>
)
[127] => Array
(
[color] =>
[name] => 34
[nbr] => 2
[url_name] => taille-34
[meta_title] =>
)
);
Thanks in adv :)
I would go with uasort, it looks much simpler to me:
// $arr is your Array
uasort($arr, function ($a, $b) {
return $a['name'] - $b['name'];
});
Here is an example: http://sandbox.onlinephpfunctions.com/code/a9f2d1e9702834b3a35206125429739222770301
$arr being your array:
//obtain list of values to sort by
foreach ($arr as $id => $value) {
$names[$id] = $value['name'];
}
$keys = array_keys($arr);
array_multisort(
$names, SORT_ASC, SORT_NUMERIC, $arr, $keys
);
$result = array_combine($keys, $arr);
You were probably missing the last step combining the array with given keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With