1

I have removed the duplicate items for the following array, by writing:

$outcome['id'] = array_unique($outcome['id'], SORT_REGULAR);

but I'm getting undesirable JSON output

    "id": {
        "0": {
            "id": 947,
            "label": "ABCD"
        },
        "1": {
            "id": 2175,
            "label": "EFGH"
        },
        "2": {
            "id": 15,
            "label": "IJKL"
        }
}

instead of the below , which is the desirable JSON output :

"id": [
        {
            "id": 947,
            "label": "ABCD"
        },
        {
            "id": 2175,
            "label": "EFGH"
        },
        {
            "id": 15,
            "label": "IJKL"
        }
]

While debugging on PHPStorm, the result shown was in array format, but on Postman, the result is being transformed to object!

0

1 Answer 1

2

array_unique preserves keys while removing items. This means it'll remove some array entries but keep indexes of remaining items intact, resulting in non-continuous numerical indices (gaps). An array with gaps in their numerical indices or an array with non-numerical indices counts as an associative array which in JSON becomes a JSON object. You can reset the indices by using array_values like e.g.

$outcome['id']  = array_values(array_unique($outcome['id'], SORT_REGULAR));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.