Open utterances-bot opened 2 years ago
Hello Lennart,
Great article. Have you tried this approach though:
$json = '{"0": "No", "1": "Yes"}';
$array = json_decode($json, true);
echo json_encode($array, JSON_FORCE_OBJECT);
This should fix the problem at hand, as solves non-associative array is used in this case.
JSON_FORCE_OBJECT
will force even plain arrays into objects, which is not the same problem but only reversed.
>>> $a = ['foo','bar'];
=> [
"foo",
"bar",
]
>>> json_encode($a, JSON_FORCE_OBJECT);
=> "{"0":"foo","1":"bar"}"
The only safe approach is not encode to php arrays but to stdClass.
Out of the box behavior as of 8.2.4 lets you magically create nested goodness
<?php
$magic[5]['magic dictionary']['in php'] = 'is Nuts';
print_r($magic);
=> Array
(
[5] => Array
(
[array dictionary] => Array
(
[in php] => is Nuts
)
)
)
PHP: Frankenstein arrays - vazaha.blog
PHP has become quite a nice language, but there are some ugly legacies left from the past. Like the deceptive Frankenstein abomination known as the "array".
https://vazaha.blog/en/9/php-frankenstein-arrays?utterances=94c45779d222efb1eeac4530ZXq7QXaWATJ%2BOQ9taoe5WcPBuMHbFn9guT9jG6PZ%2Bk25vGScG7tKgld1DZUx%2Bq5wLROREbDXy9Ji0Tvw8X5Ah6NwcpAlxF84KA%2B7RRii2KX8RICBVcrPbGCeyp4%3D