json_encode()

I need this script to produce: {“a”:Bob,“b”:Brittany} using json_encode(). currently, it produces: “‘a’ => Bob’b’ => Brittany”
Here’s my script:


$response = "Bob, Brittany";
$respose = array($response);
$response = explode(",",$response);
$response2=  "'" . "a" . "' => " . $response[0] . "'" . "b" . "' => " . $response[1]; 

echo json_encode($response2) . '</br>'; 

  

You are doing it wrong of course…You are sending json_encode a string not an array.


$r = explode( ',', 'Bob, Brittany' );
$r = array( 'a' => trim( $r[0] ), 'b' => trim( $r[1] ) );

echo json_encode( $r );

Michael Morris, thanks for your follow-up.

Keep in mind that PHP associative arrays are MUCH more powerful than the arrays of other languages (though other languages have other data structures that offer the same degree of flexibility). Arrays in javascript must have numerical keys - where in PHP array keys are largely arbitrary.

JavaScript pretty much needs to use object hashes to match PHP arrays. The major problem with these is iterating over them is not as straightforward as in PHP, and the order of the elements isn’t guaranteed. Javascript has a for in iteration - but this iterates over all methods as well as members making it problematic as an iteratoration method.

Both the jQuery and Prototype frameworks offer solutions to these problems (and I presume Yui and the others do as well but I’m not familiar with them). A discussion of these solutions and their merits is out of scope of the post and would be better placed in the Javascript forum.

Just keep in mind that PHP lets you get away with a lot of stunts with arrays that are flat out impossible in other languages (But that’s one of the reasons people choose PHP to begin with - it’s array iteration is one of its most powerful features). What PHP calls arrays other languages call dictionaries, hashes or objects.

logic_earth, that’s a score! Thanks for your help.

Thanks for pointing that out. Getting: [“‘a’ => Bob,‘b’ => Brittany”] instead of :
{‘a’ => Bob,‘b’ => Brittany}

Still not working though:

<?php
$response = "Bob, Brittany";
$respose = array($response);
$response = explode(",",$response);
$response2=  "'" . "a" . "' => " . $response[0] . ",'" . "b" . "' => " . $response[1]; 
echo $response2 . '</br>';
$response2 = array($response2);
echo json_encode($response2) . '</br>'; 
 
?>