我已经查看了有关在Stack Overflow上使用PHP排序多维数组的所有答案,但没有一个直接回答我的问题。
从各种答案中我了解到我应该使用php usort
函数或php array_multisort
函数,但我不知道如何将这些应用于我非常具体的数组结构:
这是我的变量$array
:
Array
(
[0] => Array
(
[field1] => 10
[field2] => 100
[field3] => 100
[subarray] => Array
(
[0] => Array
(
[field1] => 10
[field2] => 100
[field3] => 100
)
[1] => Array
(
[field1] => 10
[field2] => 100
[field3] => abcORDERBYTHIS
)
)
)
[1] => Array
(
[field1] => 10
[field2] => 100
[field3] => 100
[subarray] => Array
(
[0] => Array
(
[field1] => 10
[field2] => 100
[field3] => 100
)
[1] => Array
(
[field1] => 10
[field2] => 100
[field3] => ghiORDERBYTHIS
)
)
)
[2] => Array
(
[field1] => 10
[field2] => 100
[field3] => 100
[subarray] => Array
(
[0] => Array
(
[field1] => 10
[field2] => 100
[field3] => 100
)
[1] => Array
(
[field1] => 10
[field2] => 100
[field3] => defORDERBYTHIS
)
)
)
)
我希望能够通过field3
中 last 数组的subarray
对此数组进行排序。使用php end
函数可以很容易地访问这个元素:
<?php
foreach($array as $array_single){
foreach(end($array_single['subarray']) as $sub_array){
echo $sub_array;
}
}
?>
从现在开始,我一直困扰着如何按字母顺序对这个多维数组进行排序,以便得到以下结果:
$array[0]
- 由于field3
值为abcORDERBYTHIS
$array[2]
- 跳到中间,因为field3
值为defORDERBYTHIS
$array[1]
- 现在位于底部,因为field3
值为ghiORDERBYTHIS
提前致谢!
答案 0 :(得分:1)
试试这段代码:
$array = Array();
$arraytemp['field1'] = 10;
$arraytemp['field2'] = 100;
$arraytemp['field3'] = 100;
$arraytemp['subarray'][0]["field1"] = 10;
$arraytemp['subarray'][0]["field2"] = 100;
$arraytemp['subarray'][0]["field3"] = 100;
$arraytemp['subarray'][1]["field1"] = 10;
$arraytemp['subarray'][1]["field2"] = 100;
$arraytemp['subarray'][1]["field3"] = "abcORDERBYTHIS";
$array[] = $arraytemp;
$arraytemp['field1'] = 10;
$arraytemp['field2'] = 100;
$arraytemp['field3'] = 100;
$arraytemp['subarray'][0]["field1"] = 10;
$arraytemp['subarray'][0]["field2"] = 100;
$arraytemp['subarray'][0]["field3"] = 100;
$arraytemp['subarray'][1]["field1"] = 10;
$arraytemp['subarray'][1]["field2"] = 100;
$arraytemp['subarray'][1]["field3"] = "ghiORDERBYTHIS";
$array[] = $arraytemp;
$arraytemp['field1'] = 10;
$arraytemp['field2'] = 100;
$arraytemp['field3'] = 100;
$arraytemp['subarray'][0]["field1"] = 10;
$arraytemp['subarray'][0]["field2"] = 100;
$arraytemp['subarray'][0]["field3"] = 100;
$arraytemp['subarray'][1]["field1"] = 10;
$arraytemp['subarray'][1]["field2"] = 100;
$arraytemp['subarray'][1]["field3"] = "defORDERBYTHIS";
$array[] = $arraytemp;
// Sort the multidimensional array
usort($array, "custom_sort");
// Define the custom sort function used in usort
function custom_sort($a,$b) {
return strcmp($a['subarray'][1]["field3"], $b['subarray'][1]["field3"]);
}