Shuzuka Shuzuka - 3 months ago 10
PHP Question

Check if an entry matches another entry in the same array in PHP

currently i have an Array looking like this:

Array ( [searchKeyword] => kubota [searchUniques] => 361 )

Array ( [searchKeyword] => deutz dx [searchUniques] => 357 )

Array ( [searchKeyword] => kubota [searchUniques] => 350 )


As you can see kubota is a double entry.
I've tried using a for loop to check if the entry is double but its not really working out.

My intention is the following:

When there's a double entry i want to remove the double entry and add the 'searchUniques' to the then unique entry.

Expected outcome array:

Array ( [searchKeyword] => kubota [searchUniques] => 711 )

Array ( [searchKeyword] => deutz dx [searchUniques] => 357 )


I hope this makes sense.

Answer

If you want to add the number of search for a keyword, you can do this :

$arr = array(
    array(
        'searchKeyword' => 'kubota',
        'searchUniques' => 361,
    ),
    array(
        'searchKeyword' => 'deutzdx',
        'searchUniques' => 361,
    ),
    array(
        'searchKeyword' => 'kubota',
        'searchUniques' => 350
    ),
);

$newArr = array();

foreach($arr as $data){
    $keyword = $data['searchKeyword'];

    if(!isset($newArr[$keyword])){
        $newArr[$keyword] = array(
            'searchKeyword' => $keyword,
            'searchUniques' => 0,
        );
    }

    $newArr[$keyword]['searchUniques'] += $data['searchUniques'];
}

It creates this array :

array (
  'kubota' => 
  array (
    'searchKeyword' => 'kubota',
    'searchUniques' => 711,
  ),
  'deutzdx' => 
  array (
    'searchKeyword' => 'deutzdx',
    'searchUniques' => 361,
  ),
)

Hope this helps.