Want to see something scary and hacky? Check this out – it takes in a PHP array and makes a JSON message out of it:
[php]
function build($arr,&$str,$lvl=0,$in_arr=”){
$lvl++;
foreach($arr as $key => $value){
if(is_array($value)){
$str.=(($in_arr==1)?'{‘:”).'”‘.$key.'”: ‘;;
if(count($value)>1){ $str.='[‘;
}elseif(count($value)==1){ $str.=”;
}else{ $str.='{‘; }
build($value,$str,$lvl,1);
if(count($value)>1){ $str.=’]’;
}elseif(count($value)==1){ $str.=”;
}else{ $str.=’}’; }
$str.=($in_arr==1) ? ‘}’ : ”;
$str.=(next($arr)) ? ‘,’ : ”;
}else{
$str.=($lvl>1) ? ‘{‘ : ”;
$str.='”‘.$key.'”:”‘.$value.'”‘;
$str.=($lvl>1) ? ‘}’ : ”;
$str.=(next($arr)) ? ‘,’ : ”;
}
}
}
[/php]
And, of course, a sample of how to use it:
[php]
$my_data=array(
“foo”=>”1”,
“bar”=>”2”,
“baz”=>array(
“one”=>”1”,
“two”=>”2”
),
“test”=>array(
“my_test”=>array(
“one_more”=>”1″,”three_more”=>”test”
),
“your_test”=>array(
“two_more”=>”2”
),
“nest1″=>array(
“nest2″=>array(
“nest”=>”test”
)
)
),
“meedle”=>”squeedle”
);
$str=”;
build($my_data,$str);
echo ‘{‘.$str.’}’;
[/php]
Be afraid. Be very afraid 🙂