如何从单个数组中删除和连接重复值
问题描述:
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!
答
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);
?>