Home > Net >  What is php equivalent of Reduce in javascript to filter the duplicate entries in Array?
What is php equivalent of Reduce in javascript to filter the duplicate entries in Array?

Time:05-26

I am filtering array which have same value for key E.g Javascript

var sims = [{icon:"sim"},{icon:"airtime"},{icon:"sim"}]
sims.reduce((a,v)=>{
  var exists = a.some((i)=>{
    return i.icon == v.icon
  })
  if(!exists){
    a.push(v);
  }
  return a
},[])

So above code works perfectly fine and I got output Output of javascript code

But I am unable to do same thing in php I have use php array_reduce function but I am not able to understand its working as I am more puzzled with it's syntax

This is what i tried Php

<?php
$cars = array(array("icon"=>'sim'),array("icon"=>'airtime'),array("icon"=>'sim')); 
$container = array();
$unique_types = array_unique(array_map(function($elem){return $elem['icon'];}, $cars));

echo json_encode($unique_types);

?>

Which gives me output

["sim","airtime"]

It is giving me unique items which I want but not returning me the whole object as in Javascript. What am I missing?

CodePudding user response:

You can achieve this multiple ways, since your array never changes, you can use the SORT_REGULAR flag to compare items normally.

// [{"icon":"sim"},{"icon":"airtime"}]
echo json_encode(array_unique($cars, SORT_REGULAR));

This is referenced in the documentation under "FLAGS".


The above will only compare that the entire array is the same. If your array gets bigger, you may want to only unique based on the icon key.

// [{"icon":"sim"},{"icon":"airtime"}]
echo json_encode(array_intersect_key($cars, array_unique(array_column($cars, 'icon'))));

You can read up on array_column and array_intersect_key. Essentially, array_column is doing your array_map logic which then the only thing you was missing is then mapping those keys back.

CodePudding user response:

In the place of hole in the language where array_uunique() should be [again, this was never implemented] you can use a quirk of PHP's associative arrays to enforce the uniqueness.

$cars = array(array("icon"=>'sim'),array("icon"=>'airtime'),array("icon"=>'sim'));

// duplicate indexes are overwritten
$index = array_flip(array_column($cars, 'icon'));

$out = [];
foreach($index as $i) {
    $out[] = $cars[$i];
}

var_dump($out);

Output:

array(2) {
  [0]=>
  array(1) {
    ["icon"]=>
    string(3) "sim"
  }
  [1]=>
  array(1) {
    ["icon"]=>
    string(7) "airtime"
  }
}

Ref:

CodePudding user response:

Many ways to do this - for instance, try this:

$cars = array(
  array("icon"=>'sim'),
  array("icon"=>'airtime'),
  array("icon"=>'sim')); 

echo json_encode(array_map("unserialize",
              array_unique(array_map("serialize", $cars))));

Please check the documentation of these functions, the explanations are pretty straightforward. Hope this helps.

  • Related