PHP determines whether a two-dimensional array stores the same value?
过去多啦不再A梦
过去多啦不再A梦 2017-05-27 17:43:19
0
2
709
  1. Determine whether the arrays are the same based on multiple keys

  2. In the same row, each value is added

  3. This is my idea, splice the keys together as one key, and then you can judge based on only one key? Do you have any other methods?

<?php

$test = [
    [
        'name' : 'a',
        'age' : 12,
        'number' : 11,
        'score' : 50,
    ],
    [
        'name' : 'a',
        'age' : 12,
        'number' : 11,
        'score' : 30,
    ],
    [
        'name' : 'b',
        'age' : 12,
        'number' : 12,
        'score' : 50,
    ],
]

For example, for an array like this, check whether it is repeated based on name number age. If it is repeated, add the scores.

过去多啦不再A梦
过去多啦不再A梦

reply all(2)
滿天的星座

Thanks for the invitation!

    <?php

    $test = [
        [
            'name'   => 'a',
            'age'    => 12,
            'number' => 11,
            'score'  => 50,
        ],
        [
            'name'   => 'a',
            'age'    => 12,
            'number' => 11,
            'score'  => 30,
        ],
        [
            'name'   => 'b',
            'age'    => 12,
            'number' => 12,
            'score'  => 50,
        ]
    ];
    
    $arr = array();
    foreach($test as $val) {
        $key = $val['name'] . '-' . $val['age'] . '-' . $val['number'];
        $arr[$key]['name']    = $val['name'];
        $arr[$key]['age']     = $val['age'];
        $arr[$key]['number']  = $val['number'];
        $arr[$key]['score']  += $val['score'];
    }
    
    var_dump("<pre>", array_values($arr));die;
世界只因有你

Brother, I wrote you the simplest method to remove weights, take it and use it.

function uniqueArr($arr){
    $returnArr=[];
    
    //分隔符
    $separator="~!#!!#~#!!";
    //排序
    sort($arr);
    
    //去重
    foreach($arr as $value){
        $k=$value['name'].$separator.$value['number'].$separator.$value['age'];
        $returnArr[$k]=[
            'name'=>$value['name'],
            'number'=>$value['number'],
            'age'=>$value['age']
        ];//这里是去重
        $returnArr[$k]['score']+=$value['score'];//这里是累加
    }
    return $returnArr;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template