PHP中的自定义数组排序

时间:2014-09-23 09:50:23

标签: php arrays sorting

我有一个5级嵌套数组,我想以自定义方式对其进行排序。

经过一些排序后,结构是:

[shortcode1] => Array
    (
        [country1] => Array
            (
                [count] => 10
                [revenue_value] => 11
            )

    )

[shortcode2] => Array
    (
        [country1] => Array
            (
                [count] => 24
                [revenue_value] => 52
            )

    )
[shortcode3] => Array
    (
        [country2] => Array
            (
                [count] => 25
                [revenue_value] => 52
            )

    )

我想要的结果是按国家/地区对数组进行分组,并将其设置为:

[country1] => Array
(
    [count] => 34            // sum of all counts of country1
    [revenue_value] => 63    // sum of all revenue_values of country1
)
[country2] => Array
(
    [count] => 25            // sum of all counts of country2
    [revenue_value] => 52    // sum of all revenue_values of country2
)

到目前为止,这是我的代码:

        <?php foreach ($country_shortcode as $shortcode): 
            $count = 0; 
            $revenue = 0;
            ?>
            <?php foreach ($shortcode as $country=>$value): ?>
                <?php 
                    $count += $value['count'];
                    $revenue += $value['revenue_value'];
                    $country_sum[$country] = array(
                            'count' => $count,
                            'revenue' => $revenue,
                        ); 
                    ?>
            <?php endforeach; ?>
        <?php endforeach; ?>

但它只显示每个国家/地区的最后一个值

更新+答案:

这是更新的代码,完全符合我的要求。

        $country_data;
        <?php foreach ($country_shortcode as $shortcode): 
            $count = 0; 
            $revenue = 0;
            ?>
            <?php foreach ($shortcode as $country=>$value): ?>
                <?php 
                    if (!isset($country_sum[$country])) $country_sum[$country] = array('count' => 0, 'revenue'=>0);
                    $country_sum[$country]['count'] += $value['count'];
                    $country_sum[$country]['revenue'] += $value['revenue_value'];
                ?>
            <?php endforeach; ?>
        <?php endforeach; ?>

1 个答案:

答案 0 :(得分:0)

这太简单了......只需在数组上循环创建一个新的

foreach ($array as $sub) {
  foreach ($sub as $countryName => $data) {
    if (!isset($result[$countryName])) {
       $result[$countryName] = ['count' => 0, 'revenue_value' => 0];
    }
    $result[$countryName]['count'] += $data['count'];
    $result[$countryName]['revenue_value'] += $data['revenue_value'];
  }
}