dragon456101 2015-09-07 17:42
浏览 24
已采纳

如何从单个数组中删除和连接重复值

I have the next array with a duplicate value but just first position :

array(3){
[0]=> array(5){
    [0]=>'user1',
    [1]=>'2',
    [2]=>'0',
    [3]=>'0',
    [4]=>'0',
},
[2]=> array(5){
    [0]=>'user2',
    [1]=>'0',
    [2]=>'0',
    [3]=>'0',
    [4]=>'0'
},
[3]=> array(5){
    [0]=>'user1',
    [1]=>'0',
    [2]=>'0',
    [3]=>'0',
    [4]=>'4'
}}


$newArray = array();
        foreach ($array as $key) {
        $tmparray [] = array($key[0]);
            foreach ($tmparray as $keytmp) {
                if ($keytmp[0]==$key[0]) {
                    $position = array_search($keytmp[0], $key);                 
                    $newArray[] = array($keytmp[0]); 
                }
            }
    }

but I tried compare the value with array_search and create a new array but only create the first array,How I can create an array to join the first position and third and preserve the values position, like in the example below?

array(3){
[0]=> array(5){
    [0]=>'user1',
    [1]=>'2',
    [2]=>'0',
    [3]=>'0',
    [4]=>'4',
},
[2]=> array(5){
    [0]=>'user2',
    [1]=>'0',
    [2]=>'0',
    [3]=>'0',
    [4]=>'0',
}}

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • doutizong8099 2015-09-07 17:53
    关注

    This should work for you:

    Just loop through the array and use the first key of each subArray as key in your results array. If it isn't set yet you simply assign the subArray to the results array, otherwise just add the values to it.

    At the end you can use array_values() to reindex your array.

    <?php
    
        $result = [];
        foreach($array as $innerArray) {
            if(!isset($result[$innerArray[0]])) {
                $result[$innerArray[0]] = $innerArray;
            } else {
                $result[$innerArray[0]][1] += $innerArray[1];
                $result[$innerArray[0]][2] += $innerArray[2];
                $result[$innerArray[0]][3] += $innerArray[3];
                $result[$innerArray[0]][4] += $innerArray[4];
            }
        }
    
        $result = array_values($result);
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题