[英]Sorting a multidimensional array on a specific key
I have an array that loops through a set of a values, this is how it looks: 我有一个循环通过一组值的数组,这是它的外观:
$arr[] = array("name" => $name,
"add1" => $add1,
"add2" => $add2,
"add3" => $add3,
"postcode" => $pc,
"distance" => $distance);
Simple and quick question (although I'm struggling with the answer), I was wondering how I can sort the array into distance ascending (which is a floating number) order? 一个简单而快速的问题(尽管我在为答案苦苦挣扎),我想知道如何将数组按距离递增(这是一个浮点数)顺序排序?
Edit : 编辑 :
I think I understand what it is you want to achieve now. 我想我知道您现在想要实现什么。 Try this:
尝试这个:
function array_sort_by_column(&$array, $col, $direction = SORT_ASC) {
$sort_col = array();
foreach ($array as $key => $row) {
$sort_col[$key] = $row[$col];
}
array_multisort($sort_col, $direction, $array);
}
array_sort_by_column($arr, 'distance');
An alternative that I've found to organize my arrays is putting them as key, and then organizing with these keys. 我发现组织数组的另一种方法是将它们作为键,然后使用这些键进行组织。
Example (using your code): 示例(使用您的代码):
$arr = array();
$arr[$distance] = array("name" => $name,
"add1" => $add1,
"add2" => $add2,
"add3" => $add3,
"postcode" => $pc,
"distance" => $distance);
ksort($arr);
You can use the usort for sorting an array on personalized rules 您可以使用usort在个性化规则上对数组进行排序
<?php
function sortOnDistance($a, $b) {
if ($a['distance'] == $b['distance']) {
return 0;
}
return ($a['distance'] < $b['distance']) ? -1 : 1;
}
usort($array, "sortOnDistance");
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.