2

In the following example:

$a = new StdClass();
$a->name = 'example';
$a->items = [];

$a->items[] = 'A';
$a->items[] = 'B';
$a->items[] = 'C';

$json = json_encode($a);

The json data will be:

{"name":"example","items":["A","B","C"]}

I store it in the database. In another part of the system, this same json need to be edited, for exemple:

$a = json_decode( $json );

foreach( $a->items as $key => $item ){
   if( $item == 'A' ){
      unset( $a->items[$key];
      break;
   }
}

$json = json_encode( $a );
$decoded = json_decode( $json );

But json_encode convert the property $a->items from array to object

{"name":"example","items":{"1":"B","2":"C"}}

The $decoded output will be

stdClass Object
(
    [name] => example
    [items] => stdClass Object
        (
            [1] => B
            [2] => C
        )

)

There is a way to force json_encode to keep the array as array, without changing the structure of the rest of the object?

I tried to use several flags for both json_encode and json_decode, but nothing worked.

I use this object stored as json in several parts of the system, but only now has the need to make this type of change arisen, so it would be very inconvenient to change all the places that expect to receive an array to deal with an object.

  • Great question. The issue is that removing an array element with `unset()` does not modify the keys. `json_encode()` can only turn 0-indexed arrays with sequential keys into JSON arrays. See the linked duplicate for how to remove elements and re-index the array – Phil May 12 '23 at 00:49

0 Answers0