PHP按价格值对多维数组进行排序

标签 php arrays sorting

假设我有一个多维数组,设置如下:

$matrix[1][1]=4.54;        $matrix[2][1]="apples";  $matrix[3][1]="coles";
$matrix[1][2]=7.2140230;   $matrix[2][2]="apples";  $matrix[3][2]="safeway";
$matrix[1][3]=15.56;       $matrix[2][3]="oranges"; $matrix[3][3]="coles";
$matrix[1][4]=2.34;        $matrix[2][4]="bananas"; $matrix[3][4]="safeway";
$matrix[1][5]=27.98;       $matrix[2][5]="grapes";  $matrix[3][5]="coles";
$matrix[1][6]=17.68493403; $matrix[2][6]="oranges"; $matrix[3][6]="safeway";

我希望根据存储在第一列下的定价信息重新排列,以便 $matrix 的新顺序为:

$matrix[1][1]=2.34;        $matrix[2][1]="bananas"; $matrix[3][1]="safeway";
$matrix[1][2]=4.54;        $matrix[2][2]="apples";  $matrix[3][2]="coles"; 
$matrix[1][3]=7.2140230;   $matrix[2][3]="apples";  $matrix[3][3]="safeway";
$matrix[1][4]=15.56;       $matrix[2][4]="oranges"; $matrix[3][4]="coles";
$matrix[1][5]=17.68493403; $matrix[2][5]="oranges"; $matrix[3][5]="safeway";
$matrix[1][6]=27.98;       $matrix[2][6]="grapes";  $matrix[3][6]="coles";

实现这一目标的最佳方法是什么?我读过有关对多维数组进行排序的其他问题,但在实现时遇到了困难,因为这些示例似乎具有带有键和元素的关联数组,而我只是使用不同的数字来存储每条数据。我不想改变在数组中存储数据的方式,因为实际的脚本相当长且复杂,因此这将涉及大量的返工。

我对 PHP 完全陌生,所以如果我在这里遗漏了一些明显的东西,我深表歉意。感谢您的帮助。

编辑:感谢大家的建议,scessors 代码正是我所需要的。 Halfer - 对于你的第一个问题 - 是的,第二篇文章 - 好点,我会实现这个。再次感谢大家!

最佳答案

如果排序数组以零开头没有问题,则可以使用 array_multisort :

array_multisort(
    $matrix[1], SORT_ASC, SORT_NUMERIC,
    $matrix[2], SORT_ASC, SORT_STRING,
    $matrix[3], SORT_ASC, SORT_STRING
);

另请参阅my example .

关于PHP按价格值对多维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14673616/

相关文章:

java - 像树一样使用父引用对列表进行排序

arrays - $lookup 结果使用另一个数组中的键排序

javascript - MVC : Plugging a C++ Model into a Web-based View

javascript - 如何在提交 Bootstrap 时隐藏和显示警报 div

php - 我想要在 PHP 中使用 header() 的自定义 < title >

javascript - 更新数组模型取消选择迭代的 <Input> 元素

python - 为什么从文件中读取的 numpy 数组会消耗这么多内存?

c++ - 在 C++ 中使用 sort() 对二维字符数组进行排序

php - 我们的网站托管服务商因过度使用 MySQL 而暂停了我们的服务。有人明白为什么吗?

c# - 在 Windows 中访问和查询事件日志