...

View Full Version : json_encode



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

$array[0]="a";
$array[1]="b";
$array[2]="c";

when we do json_encode, we got

["a","b","c"]

however i do need json_encode in this way
{"0":"a","1":"b","2":"c"}

what shall we do?

kbluhm
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.

PappaJohn
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.

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

bdl
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;



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum