<?php
//-----------------------------------------------------------------------------------
//Turning a 2 dimentional PHP array into a JSON string
//    Array has first dimension as indexed array, 2nd dimension is keyed array
//The JSON string could be sent to JavaScript for processing
//-----------------------------------------------------------------------------------

$data = array( array("student_id"=>123, "fname"=>"Barbara", "lname"=>"Burns",  "sex"=>"F"),
               array("student_id"=>124, "fname"=>"David",   "lname"=>"Runyon", "sex"=>"M"),
               array("student_id"=>125, "fname"=>"Patrick", "lname"=>"Stack",  "sex"=>"M"),
             );

header("Content-type: text/plain");                             // inform the browser that 
                                                                // you are sending plain text

#---- Option 1 ----------------------------------------------

$jsonString = json_encode($data);                               //convert php array of object to JSON


#---- Option 2 ----------------------------------------------

$jsonString =  "[ \n";

foreach( $data as $row )                                        // loop thru the rows
{
        $jsonString .= "    {";

        foreach( $row as $colName => $colValue)                 // loop thru column names/values
            $jsonString .= '"'. $colName .'":"'. $colValue .'" , ';

        $jsonString = preg_replace("/, $/"," ", $jsonString);   // strip off the last comma after
                                                                // the last name/value pair
        $jsonString .= "}, \n";
}

$jsonString = preg_replace("/, \n$/"," \n", $jsonString);       // strip off the last comma 
                                                                // after the last row 
$jsonString .=  "] \n";
        
print "$jsonString";
        
?>