Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
<?php $a = 'aa,ss'; $b = explode(',', $a); $c = json_encode($b); echo $c;
This code is returning:
["aa","ss"]
I need:
{"0":"aa","1":"ss"}
So it is not a valid JSON code
JSON has two equally valid styles of formatting:
What you have is an array. What you seem to think as "valid" is an object.
To output an object with PHP's json_encode(), you can do like this:
json_encode()
json_encode($b, JSON_FORCE_OBJECT);
And you will have what you want.
Add a comment
Use JSON_FORCE_OBJECT at json_encode. Non-associative array output as object:
$a = 'aa,ss'; $b = explode(',', $a); $c = json_encode($b, JSON_FORCE_OBJECT); echo $c;
$a = 'aa,ss'; $b = explode(',', $a); $object = new stdClass(); foreach ($b as $key => $value) { $object->$key = $value; } $c = json_encode($object); echo $c;
that will output what you want
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
So it is not a valid JSON code- says who? Seems valid to me.["aa","ss"]is valid JSON