rrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrr

Reputation: 342

How can I return a JavaScript object from a PHP array?

If I define an array and I encode it with json_encode()

$array = array("a" => "element1", "b" => "element2");
echo json_encode($array);

I get

{"a":"element1","b":"element2"}

which is correct JSON. However I'm interested in the following output:

{a:"element1",b:"element2"}

Is there a way to achieve this in PHP 5.2 or should I implement it myself?

EDIT: since people started to downvote and comment that the output I want is not correct JSON, let me point out that the question reads "JavaScript object" and not "JSON". The system I'm working with wants the format I described, sadly I can't change that.

Upvotes: 0

Views: 869

Answers (1)

BenM
BenM

Reputation: 53208

Well, if you ABSOLUTELY have to use the invalid format that you've indicated, you'll have to do write your own function to do it. Of course, this really isn't recommended, and you should look to improve the JS code for parsing the returned JSON string, rather than forcing invalid output from the PHP.

Here's a simple function that should achieve what you're looking for (at least with the given example array - you will need to modify it if you're working with a multi-dimensional array):

function custom_json_encode( $arr )
{
    $len  = count($arr);
    $i    = 1;
    $json = '{';   

    foreach( $arr as $key => $val )
    {
        $json.= $key.':"'.$val.'"';
        $json.= ($i < $len) ? ',' : '';
        $i++;
    }

    $json.= '}';

    return $json;
}

Example return:

{a:"element1",b:"element2"}

Demo

Upvotes: 1

Related Questions