本文實例講述了php簡單實作多維數組排序的方法。分享給大家供大家參考,具體如下:
之前在做一個功能的時候,必須要把資料放到二維數組裡並且排序,然後上網找找解決思路,
這時候會用到array_multisort函數, array_multisort() 函數對多個數組或多維數組進行排序
先來看一個實例
<?php $data=array( 0=>array('one'=>34,'two'=>'d'), 1=>array('one'=>45,'two'=>'e'), 2=>array('one'=>47,'two'=>'h'), 3=>array('one'=>12,'two'=>'c'), 4=>array('one'=>15,'two'=>'w'), 5=>array('one'=>85,'two'=>'r'), ); foreach($data as $val){ $key_arrays[]=$val['one']; } array_multisort($key_arrays,SORT_ASC,SORT_NUMERIC,$data); var_dump($data);
輸出結果:按鍵值one排序,如下:
array 0 => array 'one' => int 12 'two' => string 'c' (length=1) 1 => array 'one' => int 15 'two' => string 'w' (length=1) 2 => array 'one' => int 34 'two' => string 'd' (length=1) 3 => array 'one' => int 45 'two' => string 'e' (length=1) 4 => array 'one' => int 47 'two' => string 'h' (length=1) 5 => array 'one' => int 85 'two' => string 'r' (length=1)
php 多維數組排序
下面來包裝成函數方便
function my_array_multisort($data,$sort_order_field,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC){ foreach($data as $val){ $key_arrays[]=$val[$sort_order_field]; } array_multisort($key_arrays,SORT_ASC,SORT_NUMERIC,$data); rturn $data; }