2017-09-14 32 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格式,一个简单的字符串比较应该足以对它进行排序 –