1
rows": [
{
 "group": {
 "fixed_id": 56,
 "driver_licanse_limit": 3,
 "name": "cbad",
 "age_limit": 25,
 "id": 75
 },
{
 "group": {
 "fixed_id": 56,
 "driver_licanse_limit": 3,
 "name": "cbad",
 "age_limit": 25,
 "id": 75
 },
 ]

An api sends me json but it has duplicated objects inside. An example is in above. I am trying to remove duplicated objects from it. But i did not have success.

I tried to create new array and push uniques in it.

$page = json_decode($page);
    $pages =(array) $page->rows;
    $cars = [];
    array_push($cars, $pages[0]);
    foreach($cars as $c)
    {
        foreach($pages as $p)
        {
            if(!in_array($p->group->name, (array) $c))
            {
                array_push($cars, $p);
            }
        }
    }

It does nothing. Doesn't remove duplicateds. Because it compares individual. Not comparing with all $cars array.

And i know in_array doesn't work with multidimensional arrays.

yigitozmen
  • 947
  • 4
  • 23
  • 42
  • Take a look at `array_unique()` function: http://php.net/manual/en/function.array-unique.php – JustBaron Feb 23 '17 at 12:09
  • Possible duplicate of [How to remove duplicate data of JSON object using PHP](http://stackoverflow.com/questions/34986948/how-to-remove-duplicate-data-of-json-object-using-php) – Beck Yang Feb 23 '17 at 13:37

2 Answers2

2

Given the array you provided:

        $rows = [
        [
         "group"=> [
             "fixed_id"=> 56,
             "driver_licanse_limit"=> 3,
             "name"=> "cbad",
             "age_limit"=> 25,
             "id"=> 75
             ]
        ],
        [
         "group"=> [
             "fixed_id"=> 56,
             "driver_licanse_limit"=> 3,
             "name"=> "cbad",
             "age_limit"=> 25,
             "id"=> 75
             ]
         ]];

This code will work, by removing the duplicates:

    $remaped = array();
    foreach ($rows as $row) {
        $remaped[$row['group']['fixed_id']] = $row;
    }
    print_r($remaped);
Dan Ionescu
  • 3,135
  • 1
  • 12
  • 17
  • Thank you. But it's not actually array. It is json. I apply json_decode first. Your code return an error. Cannot use object of type stdClass as array – yigitozmen Feb 23 '17 at 12:23
  • if you have a json apply json_decode first like $rows = json_decode($string, true), the second parameter true it's important because it will convert the result into an asociative array – Dan Ionescu Feb 23 '17 at 12:27
1

try Using array_map function, or put some more details

$input = array_map("unserialize", array_unique(array_map("serialize", $input)));