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!

1 Answers1

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));
Salman A
  • 262,204
  • 82
  • 430
  • 521
apokryfos
  • 38,771
  • 9
  • 70
  • 114