2010-03-18 408 views
0

這裏是我的數組,我如何通過saleref對它進行排序?排序關聯數組PHP

Array 
(
    [xml] => Array 
     (
      [sale] => Array 
       (
        [0] => Array 
         (
          [saleref] => 12345 
          [saleline] => 1 
          [product] => producta 
          [date] => 19/ 3/10 
          [manifest] =>  0 
          [qty] =>  1 
          [nextday] => 
          [order_status] => 
         ) 

        [1] => Array 
         (
          [saleref] => 12344 
          [saleline] => 1 
          [product] => productb 
          [date] => 18/ 3/10 
          [manifest] => 11892 
          [qty] =>  1 
          [nextday] => 
          [order_status] => 
         ) 
+0

重複:http://stackoverflow.com/questions/2426917/how-do-i-排序-A-多維陣列接一個的最場的最-內陣列中 – 2010-03-18 10:53:02

回答

0

例如,通過使用uasort()

示例腳本:

$data = getData(); 
uasort($data['xml']['sale'], function($a, $b) { return strcasecmp($a['saleref'], $b['saleref']); }); 
print_r($data); 

function getData() { 
return array(
    'xml' => array(
    'sale' => array (
     array(
     'saleref' => '12345', 
     'saleline' => 1, 
     'product' => 'producta', 
     'date' => '19/ 3/10', 
     'manifest' => 0, 
     'qty' => 1, 
     'nextday' => false, 
     'order_status' => false 
    ), 

     array(
     'saleref' => '12344', 
     'saleline' => 1, 
     'product' => 'productb', 
     'date' => '18/ 3/10', 
     'manifest' => 11892, 
     'qty' => 1, 
     'nextday' => false, 
     'order_status' => false 
    ) 
    ) 
) 
); 
} 
5
function cmp($a, $b) { 
    if ($a['saleref'] == $b['saleref']) { 
     return 0; 
    } 
    return ($a['saleref'] < $b['saleref']) ? -1 : 1; 
} 

uasort($array['xml']['sale'], 'cmp'); 
1

如果你需要使用maintain index associationuasort()

否則usort()would work

實施例的代碼,從手動註釋擡起和調整:

function sortSalesRef($a, $b) { 

    $a = $a['saleref']; 
    $b = $b['saleref']; 

    if ($a == $b) { 
     return 0; 
    } 

    return ($a < $b) ? -1 : 1; 

} 

usort($xml['xml']['sale'], 'sortSalesRef'); 
0
<?php 
// Comparison function 
function cmp($a, $b) 
{ 
    if ($a == $b) 
     { 
      return 0; 
     } 
    return ($a < $b) ? -1 : 1; 
} 
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4); 
print_r($array); 
uasort($array, 'cmp'); 
print_r($array); 
?>