Salve a tutti!
Volevo condividere con vuoi una semplice funzione da me creata che prende come argomento un array associativo frutto di un mysql_fetch_assoc(); e restituisce la sintassi per definire un oggetto JSON.

Esempi di utilizzo:

in php
print "var response=".jsoner($ar);
//dove $ar è qualcosa di simile :>
array(0=>array("id"=>"3","title"=>"hello world"),
1=>array("id"=>"6","title"=>"ciao mondo")); il tipico array restituito da mysql_fetch_assoc();
//e stamperà

var response= {"0":{"id":"3","title":"hello world"},"1":
{"id":"6","title":"ciao mondo"};

In javascript normale, jQuery o altro framework

eval(responseFromServer); //ritorna l'oggetto "response";
alert(response.1.title); //crea una finestra di alert con "ciao mondo" ed è possibile usare anche la forma response[1].title

Ecco il codice sorgente:

<?php
//PHP Jsoner 0.9 by resetstudio
// mysql->php->js data exchange function
// works with php 4.0+

function jsoner($ar)
{
$res=null;
$ir=0;
if(is_array($ar))
{
$res="{";
foreach($ar as $aro)
{
$res.="\"$ir\" : {";
$post_k=array_keys($aro);
$post_v=array_values($aro);
for($i=0;$i<= count($post_k)-1; $i++)
{
if(is_string($post_v[$i]))
{
$res.="$post_k[$i] : \"$post_v[$i]\" , ";
}
else $res.="$post_k[$i] : $post_v[$i] , ";
}
$res=substr($res,0,-2)."},";
$ir++;
}
if ($res != null)
{
$res=substr($res,0,-1)."};";
}
}
return $res;

}

?>


Antonio ResetStudio