Search code examples
sqlarraysjsonobjectpear

Output as Array instead of object?


I have the following code which outputs the data as objects:

    <?php

require_once('DB.php');
include "/diska/www/include/coa123-13-connect.php"; //to provide $username1,$password1

$host='co-project.lboro.ac.uk';
$dbName='coa123wdb';
$db=DB::connect("mysql://$username1:$password1@$host/$dbName");

if(DB::isError($db)){die($db->getMessage());} 

$sql=$_REQUEST['sql'];

$db->setFetchMode(DB_FETCHMODE_ASSOC);

$results = $db->getAll($sql);
if (PEAR::isError($results)){die($results->getMessage());}

echo json_encode($results);

?>

which output looks like:

[{"name":"Haslegrave Hotel","capacity":"200","weekend_price":"2000","weekday_price":"1500","licensed":"0","grade":"1","cost":"7"},{"name":"Forest Inn","capacity":"260","weekend_price":"1800","weekday_price":"1600","licensed":"1","grade":"1","cost":"6"},{"name":"Southwestern Estate","capacity":"500","weekend_price":"4000","weekday_price":"3000","licensed":"0","grade":"1","cost":"8"}]

I would like it to be outputed as an array like:

[["Haslegrave Hotel","200","2000","1500","0","1","7"],["Forest Inn","260","1800","1600","1","1","6"],["Southwestern Estate","500","4000","3000","0","1","8"]]

Any ideas how to change this?


Solution

  • json_encode simply converts your data to a json representation as is no matter what. The only way for you to have it output as an array is to have the array that you pass into json_encode be a normal array, with no string keys. That is, not an associative array.

    I don't know if it'll be enough, but you might get away with just changing the fetch mode: $db->setFetchMode(DB_FETCHMODE_ORDERED)