Dawid Góra
Dawid Góra

Reputation: 165

json_encode returns invalid json format (for me)

<?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

Answers (3)

Dima
Dima

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

MustDie1Bit
MustDie1Bit

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

Jivan
Jivan

Reputation: 23038

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.

Upvotes: 4

Related Questions