2016-01-28 23 views
1

我需要通過子數組中的值對我的多維數組進行排序。在下面的數組示例中,我需要通過子值「revenue_certificate」對父數組進行排序。PHP,由子數組排序多維數組

function custom_sort($a, $b) { 
    return strcmp($a['revenue_certificate'], $b['revenue_certificate']); 
} 

usort($data_array, 'custom_sort'); 

我覺得我快到了,但是我根本不明白的是如何引用「revenue_certificate」的子數組值。

Array 
(
    [0] => Array 
     (
      [company_id] => 130 
      [company_name] => Eureka/Brookings 
      [revenue_certificate] => 3 
      [revenue_cash] => 33 
      [average_sale] => 0 
      [total_orders] => 0 
      [certificates_per_order] => -1 
      [revenue_per_certificate] => -1 
      [visible_items] => 25 
      [retail_value] => -1 
      [average_discount] => -1 
      [new_advertisers] => 1 
      [emails_harvested] => 1 
      [new_customers] => 1 
     ) 

    [1] => Array 
     (
      [company_id] => 82 
      [company_name] => Big Deals Across America 
      [revenue_certificate] => 1 
      [revenue_cash] => 0 
      [average_sale] => 0 
      [total_orders] => 0 
      [certificates_per_order] => -1 
      [revenue_per_certificate] => -1 
      [visible_items] => 1 
      [retail_value] => -1 
      [average_discount] => -1 
      [new_advertisers] => 0 
      [emails_harvested] => 0 
      [new_customers] => 0 
     ) 

    [2] => Array 
     (
      [company_id] => 134 
      [company_name] => Fergus Falls, MN 
      [revenue_certificate] => 2 
      [revenue_cash] => 20 
      [average_sale] => 0 
      [total_orders] => 0 
      [certificates_per_order] => -1 
      [revenue_per_certificate] => -1 
      [visible_items] => 128 
      [retail_value] => -1 
      [average_discount] => -1 
      [new_advertisers] => 129 
      [emails_harvested] => 2 
      [new_customers] => 1 
     ) 

) 

感謝您的任何幫助。

+2

你的代碼看起來不錯,有什麼問題?你有錯誤嗎? – Gavriel

+0

沒有錯誤。當運行原來的代碼時,數組按「revenue_certificate」進行排序,但它並不將「revenue_certificate」的值視爲數字,而是將其視爲字符串。例如,這可能是結果順序:0,10,11000,125,1350,20 –

回答

1

不要使用STRCMP :)

function custom_sort($a, $b) { 
    return $a['revenue_certificate'] - $b['revenue_certificate']; 
} 

usort($data_array, 'custom_sort'); 

custom_sort應該返回一個負,0,正值當$一個< $ B $ A == $ B,分別爲一個< $ B(只作爲strcmp做BTW)。

+1

工作很好!後續,但這實際上是如何工作的?它看起來只是從另一個數組中減去一個數組值。 –

0

我相信你需要使用ksort代替

排序對數組按照鍵,保持關鍵數據的相關性。這主要用於關聯數組。

+0

'ksort'看起來像是對*鍵*進行排序,而不是OP的問題,他需要根據數值對數組排序他的數組。一個特定的鍵。我是否誤解了手邊的問題和/或您的解決方案? –

+0

查看DavidG的註釋,看起來這是OP所需要的。雖然 – Eric