Shuzuka Shuzuka - 3 months ago 8
PHP Question

Add duplicates to each other in a Array (PHP)

I currently have an Array that looks like this (Pseudo for example):

Array (
[0] => Array ( [searchKeyword] => fendt [searchUniques] => 2266 )

[1] => Array ( [searchKeyword] => schlüter [searchUniques] => 1822 )

[2] => Array ( [searchKeyword] => schlüter [searchUniques] => 1725 )

[3] => Array ( [searchKeyword] => 1455 [searchUniques] => 1528 )


You can see schlüter is a duplicate in this Array. Deletion would be easy with
array_unique
but i want to add the searchUniques before deleting the duplicate.

Answer

I believe this is what you're trying to do. You want to total up the 'searchKeyword' dupes as one array item. In your example 'schluter' is a dupe keyword, so you want to total it's searchUniques as one array item for schluter.

<?php
$tmp = array ( 
    array ( 'searchKeyword' => 'fendt', 'searchUniques' => 2266 ),
    array ( 'searchKeyword' => 'schlüter', 'searchUniques' => 1822 ),
    array ( 'searchKeyword' => 'schlüter', 'searchUniques' => 1725 ),
    array ( 'searchKeyword' => '1455', 'searchUniques' => 1528 )
);

$newArray = array();

foreach ($tmp as $key => &$subArray) {
    if (!isset($newArray[$subArray['searchKeyword']])) {
        $newArray[$subArray['searchKeyword']] = $subArray['searchUniques'];
    } else {
        $newArray[$subArray['searchKeyword']] += $subArray['searchUniques'];
    }
}

var_dump($newArray);
// array(3) { ["fendt"]=> int(2266) ["schlüter"]=> int(3547) [1455]=> int(1528) }
?>
Comments