PHP array_multisort - 如何保留键值?
PHP array_multisort - how to keep the key values?
如何对多维数组进行深度排序并保留它们的键?
$array = [
'2' => [
'title' => 'Flower',
'order' => 3
],
'3' => [
'title' => 'Rock',
'order' => 1
],
'4' => [
'title' => 'Grass',
'order' => 2
]
];
foreach ($array as $key => $row) {
$items[$key] = $row['order'];
}
array_multisort($items, SORT_DESC, $array);
print_r($array);
结果:
Array
(
[0] => Array
(
[title] => Flower
[order] => 3
)
[1] => Array
(
[title] => Grass
[order] => 2
)
[2] => Array
(
[title] => Rock
[order] => 1
)
)
我追求的是:
Array
(
[2] => Array
(
[title] => Flower
[order] => 3
)
[4] => Array
(
[title] => Grass
[order] => 2
)
[3] => Array
(
[title] => Rock
[order] => 1
)
)
有什么想法吗?
你可以试试uasort:
uasort($array, function ($a, $b) { return $b['order'] - $a['order']; });
您的代码:
<?php
$array = [
'2' => [
'title' => 'Flower',
'order' => 3
],
'3' => [
'title' => 'Rock',
'order' => 1
],
'4' => [
'title' => 'Grass',
'order' => 2
]
];
uasort($array, function ($a, $b) { return $b['order'] - $a['order']; });
print_r($array);
可能这就是您要找的东西:Online Example
保留数组键,按order列排序,再组合。
$keys = array_keys($array);
array_multisort(
array_column($array, 'order'), SORT_DESC, SORT_NUMERIC, $array, $keys
);
$array = array_combine($keys, $array);
echo '<pre>';
print_r($array);
如何对多维数组进行深度排序并保留它们的键?
$array = [
'2' => [
'title' => 'Flower',
'order' => 3
],
'3' => [
'title' => 'Rock',
'order' => 1
],
'4' => [
'title' => 'Grass',
'order' => 2
]
];
foreach ($array as $key => $row) {
$items[$key] = $row['order'];
}
array_multisort($items, SORT_DESC, $array);
print_r($array);
结果:
Array
(
[0] => Array
(
[title] => Flower
[order] => 3
)
[1] => Array
(
[title] => Grass
[order] => 2
)
[2] => Array
(
[title] => Rock
[order] => 1
)
)
我追求的是:
Array
(
[2] => Array
(
[title] => Flower
[order] => 3
)
[4] => Array
(
[title] => Grass
[order] => 2
)
[3] => Array
(
[title] => Rock
[order] => 1
)
)
有什么想法吗?
你可以试试uasort:
uasort($array, function ($a, $b) { return $b['order'] - $a['order']; });
您的代码:
<?php
$array = [
'2' => [
'title' => 'Flower',
'order' => 3
],
'3' => [
'title' => 'Rock',
'order' => 1
],
'4' => [
'title' => 'Grass',
'order' => 2
]
];
uasort($array, function ($a, $b) { return $b['order'] - $a['order']; });
print_r($array);
可能这就是您要找的东西:Online Example
保留数组键,按order列排序,再组合。
$keys = array_keys($array);
array_multisort(
array_column($array, 'order'), SORT_DESC, SORT_NUMERIC, $array, $keys
);
$array = array_combine($keys, $array);
echo '<pre>';
print_r($array);