search

Home  >  Q&A  >  body text

PHP determines whether a two-dimensional array stores the same value?

  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梦2783 days ago710

reply all(2)I'll reply

  • 滿天的星座

    滿天的星座2017-05-27 17:45:19

    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;

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-27 17:45:19

    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;
    }

    reply
    0
  • Cancelreply