Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JSON encoding turns key to string when unset [duplicate]

Tags:

json

php

Can you guys help me explain what is happening here.

$data[0] = array("one" => "uno", "two" => "dos", "three" => "tres");
$data[1] = array("one" => "uno", "two" => "dos", "three" => "tres");

//unset($data[0]);

$encode = json_encode($data);

$decode = json_decode($encode);

var_dump($decode);

outputs:

array(2) { [0]=> object(stdClass)#1 (3) { ["one"]=> string(3) "uno" ["two"]=> string(3) "dos" ["three"]=> string(4) "tres" } [1]=> object(stdClass)#2 (3) { ["one"]=> string(3) "uno" ["two"]=> string(3) "dos" ["three"]=> string(4) "tres" } }

This is normal keeps it as an array but as soon as I unset a part of the array it turns it into an obj.

$data[0] = array("one" => "uno", "two" => "dos", "three" => "tres");
$data[1] = array("one" => "uno", "two" => "dos", "three" => "tres");

unset($data[0]);

$encode = json_encode($data);

$decode = json_decode($encode);

var_dump($decode);

output:

object(stdClass)#1 (1) { ["1"]=> object(stdClass)#2 (3) { ["one"]=> string(3) "uno" ["two"]=> string(3) "dos" ["three"]=> string(4) "tres" } }

How do I keep the consistency?

like image 780
Carlos Mendoza Avatar asked Jun 10 '26 01:06

Carlos Mendoza


2 Answers

I would look at json_encode at the options. I think JSON_FORCE_OBJECT should force constancy.

like image 152
ars265 Avatar answered Jun 17 '26 06:06

ars265


As Marc B explained in a comment, you need to re-index the array to zero-based indexes. In PHP that can be done with array_values:

$encode = json_encode(array_values($data));

See as well:

  • Help editing JSON to make an array rather than a 'dictionary' (Jun 2011)
like image 23
hakre Avatar answered Jun 17 '26 06:06

hakre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!