PHP,按子数组排序多维数组

时间:2016-01-28 23:46:23

标签: php sorting multidimensional-array

我需要通过子数组中的值对多维数组进行排序。在下面的数组示例中,我需要按子值“revenue_certificate”对父数组进行排序。

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
        )

)

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

不要使用strcmp:)

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

usort($data_array, 'custom_sort');
当$ a<

时,custom_sort应返回负0,正值。 $ b,$ a == $ b,$ a<分别为$ b(就像strcmp一样BTW)。

答案 1 :(得分:0)

我认为您需要使用ksort代替

按键对数组进行排序,保持数据关联的关键。这主要用于关联数组。

答案 2 :(得分:0)

Array ( [0] => Array ( [India] => 2 ) [1] => Array ( [Canada] => 1 ) [2] => Array ( [USA] => 3 ) )

还要根据国家/地区值对这种desc顺序进行排序