PHP,按子数组对多维数组排序 [英] PHP, Sort Multidimensional Array by Child Array

查看:67
本文介绍了PHP,按子数组对多维数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要按子数组中的值对多维数组进行排序.在下面的数组示例中,我需要按子值"revenue_certificate"对父数组进行排序.

I need to sort my multidimensional array by a value in the child array. In the array example below, I need to sort the parent arrays by child value "revenue_certificate".

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

usort($data_array, 'custom_sort');

我觉得自己快到了,但是我根本不了解的是如何引用"revenue_certificate"子数组的值.

I feel like I'm almost there, but where I simply don't understand is how to reference the child array value of "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
        )

)

感谢您的帮助.

推荐答案

不要使用strcmp:)

Don't use 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一样).

custom_sort should return a negative, 0, positive value when $a < $b, $a == $b, $a < $b respectively (just as strcmp does BTW).

这篇关于PHP,按子数组对多维数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆