Heim  >  Artikel  >  Backend-Entwicklung  >  PHP按指定键值对二维数组进行排序的方法_php技巧

PHP按指定键值对二维数组进行排序的方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:02:121169Durchsuche

本文实例讲述了PHP按指定键值对二维数组进行排序的方法。分享给大家供大家参考,具体如下:

问题:

有数组:

复制代码 代码如下:
array(0=>array('id'=>1,'price'=>50),1=>array('id'=>2,'price'=>60));

要求根据数组的price这个字段进行排序。

实现代码如下:

<&#63;php 
$array[] = array('id'=>1,'price'=>50);
$array[] = array('id'=>2,'price'=>70);
$array[] = array('id'=>3,'price'=>30);
$array[] = array('id'=>4,'price'=>20);
foreach ($array as $key=>$value){
  $id[$key] = $value['id'];
  $price[$key] = $value['price'];
}
array_multisort($price,SORT_NUMERIC,SORT_DESC,$id,SORT_STRING,SORT_ASC,$array);
echo '<pre class="brush:php;toolbar:false">';
print_r($array);
echo '
'; ?>

运行结果:

Array
(
[0] => Array
(
[id] => 2
[price] => 70
)
[1] => Array
(
[id] => 1
[price] => 50
)
[2] => Array
(
[id] => 3
[price] => 30
)
[3] => Array
(
[id] => 4
[price] => 20
)
)

希望本文所述对大家PHP程序设计有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn