View Full Version : json_encode

02-12-2010, 12:13 AM
i think php json_encode function is handy, however now i got a problem, i have one array


when we do json_encode, we got


however i do need json_encode in this way

what shall we do?

02-12-2010, 12:36 AM
The desired format is an object, and I don't believe object keys can be enumerated. Miht be wrong though, I'm no JavaScript super-guru.

02-12-2010, 01:06 AM
If I'm not mistaken, it's because you are using numeric indices in your array. If you change them to strings, json_encode should give what you're looking for.

02-12-2010, 02:01 AM
the problem is i need integer.

02-12-2010, 02:39 AM
You don't have to use json_encode().

$array= array(
'A', 'B', 'C'

$jsonString= '{ ';
foreach($array AS $key => $val) {
$jsonString.= "'{$key}' : '{$val}'";
if ( $key != sizeof($array)-1 ) {
$jsonString.= ', ';
$jsonString.= ' }';
echo $jsonString;