Reputation: 165
<?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"}
Upvotes: 0
Views: 2295
Reputation: 8652
$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
Upvotes: 1
Reputation: 561
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;
Upvotes: 2
Reputation: 23038
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($b, JSON_FORCE_OBJECT);
And you will have what you want.
Upvotes: 4