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.

2

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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
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
1

try Using array_map function, or put some more details

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.