我如何排序在PHP内部数组的领域之一多维数组? [英] How do I sort a multidimensional array by one of the fields of the inner array in PHP?
本文介绍了我如何排序在PHP内部数组的领域之一多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个模仿dayabase表的数组。每个数组元素reporesents一个行和每行中是包含的字段名称和值另一个阵列。
Suppose I have an array that mimics a dayabase table. Each array element reporesents a row and within each row is another array that contains the field names and values.
Array
(
[0] => Array
(
[name] => Sony TV
[price] => 600.00
)
[1] => Array
(
[name] => LG TV
[price] => 350.00
)
[2] => Array
(
[name] => Samsung TV
[price] => 425.00
)
}
我想要做的排序是按价格行(外数组元素)。下面是我想要达到一个例子:
What I want to do is sort the rows (outer array elements) by price. Below is an example of what I want to achieve:
Array
(
[0] => Array
(
[name] => LG TV
[price] => 350.00
)
[1] => Array
(
[name] => Samsung TV
[price] => 425.00
)
[2] => Array
(
[name] => Sony TV
[price] => 600.00
)
}
正如你可以看到我不需要preserve外阵的钥匙。
As you can see I don't need to preserve the keys of the outer array.
推荐答案
您需要使用 usort 一>,即通过用户定义的函数数组排序的函数。是这样的:
You need to use usort, a function that sorts arrays via a user defined function. Something like:
function cmp($a, $b)
{
if ($a["price"] == $b["price"]) {
return 0;
}
return ($a["price"] < $b["price"]) ? -1 : 1;
}
usort($yourArray,"cmp")
这篇关于我如何排序在PHP内部数组的领域之一多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文