0
<?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"}
6
  • 2
    So it is not a valid JSON code - says who? Seems valid to me. Commented Jan 31, 2014 at 23:08
  • 2
    ["aa","ss"] is valid JSON Commented Jan 31, 2014 at 23:08
  • 1
    If you need an object, check out the FORCE_OBJECT parameter php.net/json_encode Commented Jan 31, 2014 at 23:09
  • Oh, I didn't know that. But acctually I need it to be: {0: "aa",1:"ss"} or something simmilar Commented Jan 31, 2014 at 23:10
  • Thank you Pekka, please write an answer and I will give you rep Commented Jan 31, 2014 at 23:12

3 Answers 3

4

JSON has two equally valid styles of formatting:

  • Objects
  • Arrays

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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;

Comments

1
$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

1 Comment

thanks :) but i have already chosen version with JSON_FORCE_OBJECT

Your Answer

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.

Ask question

Explore related questions

See similar questions with these tags.