关php二维数组中按某个元素的值排序

array([0] => array(
['id'] => 1['type'] => '普通发票'['weight'] => 1['is_start'] => 1)
[1] => array(
['id'] => 2['type'] => '增值税专用发票'['weight'] => 2['is_start'] => 1)
[2] => array(
['id'] => 3['type'] => '收据'['weight'] => 0['is_start'] => 1)
[3] => array(
['id'] => 4['type'] => '测试'['weight'] => 4['is_start'] => 0)
)

我想重新排序数组,用weight的值来排序第一层
得到的结果的应该是如下这样:

array(
[0] => array(
['id'] => 3['type'] => '收据'['weight'] => 0['is_start'] => 1)
[1] => array(
['id'] => 1['type'] => '普通发票'['weight'] => 1['is_start'] => 1)
[2] => array(
['id'] => 2['type'] => '增值税专用发票'['weight'] => 2['is_start'] => 1)
[3] => array(
['id'] => 4['type'] => '测试'['weight'] => 4['is_start'] => 0)
)

假定这个数组的为$invoice,要如何去操作它?
PHP有很多数组函数可以利用,但是不知道哪个才是。

$fruits =array(
0 => array( 'id' => 1, 'type' => '普通发票', 'weight' => 1, 'is_start' => 1),
1 => array( 'id' => 2, 'type' => '增值税专用发票', 'weight' => 2, 'is_start' => 1),
2 => array( 'id' => 3, 'type' => '收据', 'weight' => 0, 'is_start' => 1),
3 => array( 'id' => 4, 'type' => '测试', 'weight' => 4, 'is_start' => 0)
);

var_dump($fruits);

function compare($x,$y)
{
if($x['weight'] == $y['weight'])
return 0;
elseif($x['weight'] < $y['weight'])
return -1;
else
return 1;
}
usort($fruits,"compare");
echo $fruits[0]['id']."<br />";
echo $fruits[1]['id']."<br />";
echo $fruits[2]['id']."<br />";
echo $fruits[3]['id']."<br />";
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-02-26
参考手册的array_multisort()

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网