[jQuery] PHP jsoner ver 0.9

[jQuery] PHP jsoner ver 0.9


Hi!
I want to share with you a simple function that thakes an associative
array returned from a mysql_fetch_assoc() and outputs a json object;
usage:
in php
print "var response=".jsoner($ar);
//where $ar is somethin like that :>
array(0=>array("id"=>"3","title"=>"hello world"),
1=>array("id"=>"6","title"=>"ciao mondo")); the typical array returned
by mysql_fetch_assoc();
//it will output:
var response= {"0":{"id":"3","title":"hello world"},"1":
{"id":"6","title":"ciao mondo"};
in jQuery or normal javascript
eval(responseFromServer); //returns the "response" object;
alert(response.1.title); //will output "ciao mondo" and you can use
the form response[1].title too
Here we go:
<?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;
}
?>