PHP自定义数组合并功能不起作用

时间:2017-09-14 13:08:27

标签: 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
                )

        )

任何人都可以帮助我如何排序两个键,第一个是Create_date = ASC,第二个是Type = DESC?抱歉我的英语不好。如果可以的话,请尽量提高这个问题的可读性。感谢您的帮助。

有人要求付款和发票。我发布了两个阵列。现在请帮助我。

1 个答案:

答案 0 :(得分: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;
    }
);