Why does unset () change the way json_encode string is formatted?

I noticed something interesting today using unset () and json_decode / json_encode. Here is the code:

echo "<h3>1) array as string</h3>";
$sa = '["item1","item2","item3"]';
var_dump($sa);
echo "<h3>2) array as string decoded</h3>";
$sad = json_decode($sa);
var_dump($sad);
echo "<h3>3) array as string decoded, then encoded again. <small>(Note it the same as the original string)</small></h3>";
$sade = json_encode($sad);
var_dump($sade);
echo "<h3>4) Unset decoded</h3>";
unset($sad[0]);
var_dump($sad);
echo "<h3>5) Encode unset array. <small>(Expecting it to look like original string minus the unset value)</small></h3>";
$ns = json_encode($sad);
var_dump($ns);
echo "<h3>6) Decode Encoded unset array</h3>";
var_dump(json_decode($ns));

      

and the result is: enter image description here

So my question is, why does unset () change the way json_encode makes it a string? And how can I achieve the same string format as the original?

+3


source to share


2 answers


json does not need to include keys for a continuous key sequence from scratch.

Canceling a value from a standard enumerated array leaves a gap in the key sequence for that array; it does not regulate the remaining keys in any way; so the json should reflect this difference including keys

If you want to reset the keys to the contiguous sequence again from offset 0, then



unset($sad[0]);
$sad = array_values($sad);

      

and then json encode / decode again

Demo

+4


source


In number 5, if you notice the keys start with 1

. Usually arrays (in both php and js / json) start at zero. The optional indexed array (or array with non-overlapping numbers) in json is an object literal, not an array. If you want the same string format, I suggest you pass json_decode to the second parameter to force it into the array. Then you can use array functions that reindex the array as numeric, such as array_shift or array_pop . Or when json_encoding the array, reindex the array yourself with array_values .



+4


source







All Articles