I'm new to stackoverflow and I need some help.
I'm trying to remove the duplicates from a multi-dimension array in PHP such as:
Array (
[0] => Array ( [Plat] => hello [Data] => 01/01/2015 [Term] => PHP [Quan] => 1 )
[1] => Array ( [Plat] => hello [Data] => 01/01/2015 [Term] => PHP [Quan] => 1 )
[2] => Array ( [Plat] => hello [Data] => 03/01/2015 [Term] => PHP [Quan] => 1 )
[3] => Array ( [Plat] => hello [Data] => 03/01/2015 [Term] => PHP [Quan] => 1 )
[4] => Array ( [Plat] => hello [Data] => 03/01/2015 [Term] => PHP [Quan] => 1 )
[5] => Array ( [Plat] => hello [Data] => 03/01/2015 [Term] => PHP [Quan] => 1 )
)
and create an array that removes the duplicates and adds to Quan
the number of duplicates it as found like this (filtered by data) :
Array (
[0] => Array ( [Plat] => hello [Data] => 01/01/2015 [Term] => PHP [Quan] => 2 )
[1] => Array ( [Plat] => hello [Data] => 03/01/2015 [Term] => PHP [Quan] => 4 )
)
My code is the folowing: ($top
is the array)
foreach($top as $value){
if(!empty($temp_top)){
for($i =0;$i<sizeof($temp_top);$i++){
if($value['Data'] == $temp_top[$i]['Data'] ){
$temp_top[$i]['Quan'] +=1;
}else{
$temp_top[] = $value;
}
}
}else{
$temp_top[] = $value;
}
}
I've tried some answers that I found here on stack such as:
$input = array_map("unserialize", array_unique(array_map("serialize", $top)));
but I can't add how many there are to Quan
.
I found a solution myself with the help of other posts.
Here is a sample of my code:
if someone can help me make this code more beautifull I would be in your debt :)
thanks everyone tho!
You will need to implement temporary keys so that as you iterate your array, you can determine if you are handling the first occurrence of
Data
or not. If not, you merely add the currentQuan
value to the first occurrence'sQuan
value.When finished looping, you remove the temporary keys (reindex) by calling
array_values()
.Code: (Demo)
Output:
*Note if you want to ignore the
Quan
value and just add1
each time, you can use:Your question is ambiguous on this logic because of the
Quan
column data.