2013-07-05 25 views
1

我需要排序在價格的功能像這樣的數組:如何排序複雜的多維數組

Array 
(
    [SJ] => Array 
     (
      [desc] => Junior Suite 
      [solutions] => Array 
       (
        [0] => Array 
         (
          [code] => BB 
          [desc] => Bed and Breakfast 
          [price] => 607.08 
          [status] => OK 
          [policy] => 1 
          [currency] => EU 
         ) 
        [1] => Array 
         (
          [code] => BB 
          [desc] => Bed and Breakfast 
          [price] => 700.80 
          [status] => OK 
          [policy] => 1 
          [currency] => EU 
         ) 

       ) 

     ) 

    [MZ] => Array 
     (
      [desc] => Doble Deluxe con hidromasaje 
      [solutions] => Array 
       (
        [0] => Array 
         (
          [code] => BB 
          [desc] => Bed and Breakfast 
          [price] => 518.40 
          [status] => OK 
          [policy] => 1 
          [currency] => EU 
         ) 

       ) 

     ) 

) 

能有人給我做了正確的方式? :)

預期的結果

Array 
(
    [MZ] => Array 
     (
      [desc] => Doble Deluxe con hidromasaje 
      [solutions] => Array 
       (
        [0] => Array 
         (
          [code] => BB 
          [desc] => Bed and Breakfast 
          [price] => 518.40 
          [status] => OK 
          [policy] => 1 
          [currency] => EU 
         ) 

       ) 

     ) 
    [SJ] => Array 
     (
      [desc] => Junior Suite 
      [solutions] => Array 
       (
        [0] => Array 
         (
          [code] => BB 
          [desc] => Bed and Breakfast 
          [price] => 607.08 
          [status] => OK 
          [policy] => 1 
          [currency] => EU 
         ) 
        [1] => Array 
         (
          [code] => BB 
          [desc] => Bed and Breakfast 
          [price] => 700.80 
          [status] => OK 
          [policy] => 1 
          [currency] => EU 
         ) 

       ) 

     ) 
) 

我需要的是訂購價格的功能陣列。 所以,如果我有很多的解決方案,我需要的是有輕微的價格

+2

** 1)**您嘗試過什麼? ** 2)**預期產出是多少? – HamZa

回答

2

您可以使用PHP函數usort這樣的一個:

function sortInnerPrice($a, $b) { 
    if ($a['price'] == $b['price']) { 
     return 0; 
    } 

    return ($a['price'] < $b['price']) ? -1 : 1; 
} 

// First sort the inner prices 
foreach ($test as $key => $val) { 
    usort($test[$key]['solutions'], 'sortInnerPrice'); 
} 

function cmp($a, $b) 
{ 
    $aPrice = $a['solutions'][0]['price']; 
    $bPrice = $b['solutions'][0]['price']; 
    if ($aPrice == $bPrice) { 
     return 0; 
    } 
    return ($aPrice < $bPrice) ? -1 : 1; 
} 

// Then sort by lowest solution price 
usort($yourArray, "cmp"); 

usort是一個PHP函數,使您可以根據任何你想要的數組排序。創建一個函數,如果它們相同,則返回0;如果$ a之前需要$ a,則返回-1;如果$ b之後需要$ a,則返回1。

+0

對不起,這是我的錯誤..我有很多解決方案..在那個例子中只有一個..但通常有很多解決方案.. – JackTurky

+0

你想如何排序。平均解決方案?最低的解決方案?最高解決方案 – chrislondon

+0

請參閱編輯。.. :) – JackTurky

0

儘量讓包含所有價格,然後另一個數組使用array_multisort