2017-09-14 69 views
1

PHP代碼:PHP自定義的數組合並功能不能正常工作

$data['Ledgers'] = array_merge($data['Invoices'],$data['Payments']); 
usort($data['Ledgers'], function($a, $b) {return strtotime($a["Create_date"]) - strtotime($b["Create_date"]);}); 

輸出:

[Ledgers] => Array 
     (
      [0] => Array 
       (
        [Title] => Cash 
        [Create_date] => 2017-09-14 
        [Amount] => 12000 
        [Type] => Credit 
       ) 

      [1] => Array 
       (
        [Title] => 24 
        [Create_date] => 2017-09-14 
        [Amount] => 12600 
        [Type] => Debit 
       ) 
      [2] => Array 
       (
        [Title] => 25 
        [Create_date] => 2017-09-14 
        [Amount] => 1000 
        [Type] => Debit 
       ) 

     ) 
[Payments] => Array 
    (
     [0] => Array 
      (
       [Title] => Cash 
       [Create_date] => 2017-09-14 
       [Amount] => 12000 
       [Type] => Credit 
      ) 

    ) 

[Invoices] => Array 
    (
     [0] => Array 
      (
       [Title] => 24 
       [Create_date] => 2017-09-14 
       [Amount] => 12600 
       [Type] => Debit 
      ) 

    ) 

預期輸出:

[Ledgers] => Array 
     (

      [0] => Array 
       (
        [Title] => 24 
        [Create_date] => 2017-09-14 
        [Amount] => 12600 
        [Type] => Debit 
       ) 
      [1] => Array 
       (
        [Title] => 25 
        [Create_date] => 2017-09-14 
        [Amount] => 1000 
        [Type] => Debit 
       ) 
      [2] => Array 
       (
        [Title] => Cash 
        [Create_date] => 2017-09-14 
        [Amount] => 12000 
        [Type] => Credit 
       ) 

     ) 

任何人都可以幫助我我如何排序的兩個鍵1是Create_date = ASC,第二種是Type = DESC?對我弱的英語感到抱歉。如果可以,請嘗試提高此問題的可讀性。你的幫助表示讚賞。

有人要求付款和發票。我發佈了兩個數組。現在請幫助我。

+0

檢查:https://stackoverflow.com/questions/9260343/php-usort-sorting-multiple-fields –

+0

你可以爲這兩個'$提供一些樣本數據數據['發票']和'$數據['付款']'請? – Scoots

+0

你需要修改你的usort()函數:如果兩個日期相等,則比較類型並返回-1,+1或零。 – Calimero

回答

1

像這樣的東西應該工作:

usort(
    $data['Ledgers'], 
    function($a, $b) { 
     $time_diff = strtotime($a["Create_date"]) - strtotime($b["Create_date"]); 

     // if time differernce is zero - return comparison of `Type` 
     // fields multiplied by `-1` to sort in descending order 
     return $time_diff === 0? -1 * strcmp($a['Type'], $b['Type']) : $time_diff; 

     // or notice comparing `$b` first, here you don't need `-1` 
     return $time_diff === 0? strcmp($b['Type'], $a['Type']) : $time_diff; 
    } 
); 
+0

,因爲'Create_date'是YYYY-MM-DD格式,一個簡單的字符串比較應該足以對它進行排序 –