php json数组排序组合总和

时间:2017-09-07 11:58:44

标签: php json sorting grouping

有没有办法对数组进行分组,排序和求和 我已经尝试了所有东西 - 有sort,array_unique,foreach等等。 以下数据是notionell。

Array
(
[0] => Array
    (
        [clientName] => Audi
        [model] => A6 
        [cost] => 40.000
    )

[1] => Array
    (
        [clientName] => Audi
        [model] => S8
        [cost] => 90.000
    )

[2] => Array
    (
        [clientName] => VW
        [model] => Golf V
        [cost] => 5.000
    )

[3] => Array
    (
        [clientName] => VW
        [model] => Golf V
        [cost] => 3.500
    )

[4] => Array
    (
        [clientName] => Audi
        [model] => RS6
        [cost] => 120.000
    )

[5] => Array
    (
        [clientName] => VW
        [model] => Passat CC
        [cost] => 35.000
    )

)

我希望有这样的输出(在html中)

Audi            total cost: 250.000
A6              40.000
S8              90.000
RS6             120.000

VW              total cost: 43.500
Golf V          8.500
Passat CC       35.000

任何想法?
谢谢你的帮助!!

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

<?php

$totals = [];
$models = [];
foreach ($array as $row) {
    $totals[$row['clientName']] += $row['cost'];
    $models[$row['clientName']][] = $row;
}

所以现在你有一个总数的数组,客户端名称作为键,以及一个包含模型数组的客户名称数组。

foreach($models as $client => $cars) {
   echo $client.' total: '.$totals[$client].'<br />';
   foreach($cars as $model) {
      echo $model['model'].' '.$model['cost'].'<br />';
   }
}

我没有测试过,所以可能需要调整,但希望thgat会为你工作!让我知道!

编辑:

<?php

$json = '[{"clientName":"Audi","model":"A6","cost":40000},{"clientName":"Audi","model":"S8","cost":90000},{"clientName":"VW","model":"GolfV","cost":5000},{"clientName":"VW","model":"GolfV","cost":3500},{"clientName":"Audi","model":"RS6","cost":120000},{"clientName":"VW","model":"PassatCC","cost":35000}]';

$array = json_decode($json, true);

$totals = [];
$makes = [];
$modelTotals = [];

foreach ($array as $row) {
    // Set defaults to suppress notices
    $totals[$row['clientName']] = isset($totals[$row['clientName']]) ? $totals[$row['clientName']] : 0;
    $modelTotals[$row['model']] = isset($modelTotals[$row['model']]) ? $modelTotals[$row['model']] : 0;

    $totals[$row['clientName']] += $row['cost'];
    $makes[$row['clientName']][$row['model']] = $row;
    $modelTotals[$row['model']] += $row['cost'];
}

foreach($makes as $client => $cars) {
   echo $client.' total: '.$totals[$client]."\n";
   foreach($cars as $model) {
      echo $model['model'].' '.$modelTotals[$model['model']]."\n";
   }
}

哪个输出:

Audi total: 250000 
A6 40000 
S8 90000 
RS6 120000 
VW total: 43500 
GolfV 8500 
PassatCC 35000

请在此处查看https://3v4l.org/kbkng

答案 1 :(得分:0)

下面的评论,自我解释片段做了特技。请注意,所有浮点值都已转换为整数。

<?php

    $arr = [
        [
            'clientName'    => 'Audi',
            'model'         => 'A6',
            'cost'          => 40000,
        ],

        [
            'clientName'    => 'Audi',
            'model'         => 'S8',
            'cost'          => 90000,
        ],

        [
            'clientName'    => 'VW',
            'model'         => 'Golf V',
            'cost'          => 5000,
        ],

        [
            'clientName'    => 'VW',
            'model'         => 'Golf V',
            'cost'          => 3500,
        ],

        [
            'clientName'    => 'Audi',
            'model'         => 'RS6',
            'cost'          => 120000,
        ],

        [
            'clientName'    => 'VW',
            'model'         => 'Passat CC',
            'cost'          =>  35000,
        ],
    ];


    // A VARIABLE TO HOLD ALL GROUPED ENTRIES
    $group      = [];
    // LOOP THROUGH THE ARRAY AND BUILD THE GROUPS BASED ON 'clientName' ENTRY
    foreach($arr as $iKey=>$rData){
        $sKey   = $rData['clientName'];

        if(!array_key_exists($sKey, $group)){
            $group[$sKey]           = ['total'=>$rData['cost'], $rData ];
        }else{
            $group[$sKey]['total'] += $rData['cost'];
            $group[$sKey][]         = $rData;
        }
    }

    // RENDER TO REFLECT THE OP's END DATA-STRUCTURE
    $result = "<table>";
    foreach($group as $clName=>$groupData){
        $result .= "<tr style='color'>";
        $result .= "<th>{$clName}</th>";
        $result .= "<th>{$groupData['total']}</th>";
        $result .= "</tr>";
        foreach($groupData as $k=>$v){
            $result .= "<tr>";
            $result .= "<td>{$v['model']}</td>";
            $result .= "<td>{$v['cost']}</td>";
            $result .= "</tr>";
        }
        $result .= "<tr><td colspan='2'>&nbsp;</td></tr>";
    }
    $result .= "</table>";

    var_dump($group);
    echo($result);

QUICK TEST HERE: enter image description here

<强>更新

要将“Golf V”添加到列表中,您可能需要在上面的代码段中添加一个额外的嵌套if条件块....这意味着要添加这样的内容:

  <?php

        if($mdlKey == 'Golf V'){
            if(!array_key_exists($mdlKey, $group)){
                $group[$mdlKey]           = ['total'=>$rData['cost'], $rData ];
            }else{
                $group[$mdlKey]['total'] += $rData['cost'];
                $group[$mdlKey][]         = $rData;
            }
        }

最后,您的主要循环结构可能如下所示:

  <?php

    // A VARIABLE TO HOLD ALL GROUPED ENTRIES
    $group      = [];
    // LOOP THROUGH THE ARRAY AND BUILD THE GROUPS BASED ON 'clientName' ENTRY
    foreach($arr as $iKey=>$rData){
        $sKey   = $rData['clientName'];
        $mdlKey = $rData['model'];

        if(!array_key_exists($sKey, $group)){
            $group[$sKey]           = ['total'=>$rData['cost'], $rData ];
        }else{
            $group[$sKey]['total'] += $rData['cost'];
            $group[$sKey][]         = $rData;
        }

        if($mdlKey == 'Golf V'){
            if(!array_key_exists($mdlKey, $group)){
                $group[$mdlKey]           = ['total'=>$rData['cost'], $rData ];
            }else{
                $group[$mdlKey]['total'] += $rData['cost'];
                $group[$mdlKey][]         = $rData;
            }
        }
    }
相关问题