1

I have two MySQL tables, one for fruits and one for vegetables, and I want to query these tables for their contents and return both sets of results in one large JSON dictionary, keyed with Fruits to return the fruit array and Vegetables to return the vegetables array. It currently doesn't work (returns null).

Here is my current code:

//query each table for every object
$fruitResult = mysql_query("SELECT * FROM Fruits");
$vegResult = mysql_query("SELECT * FROM Vegetables");

//set up an array for each kind of object
$fruits = array();
$vegetables = array();

while ($fruitRow = mysql_fetch_assoc($fruitResult)) {
    //add each result from Fruit table to array
    $fruits[] = $fruitRow;
}
while ($vegRow = mysql_fetch_assoc($vegResult)) {
    //add each result from Veggie table to array
    $vegetables[] = $vegRow;
}

//create dictionary
$dictionary = array("Fruit"=>$fruits,"Vegetables"=>$vegetables);

echo json_encode($dictionary);

I can separate each of these things out and just

echo json_encode($fruits);
echo json_encode($vegetables);

but then there are two separate arrays returned. Can anyone shed any light?
I'd like my response to look like this:

[{"Fruit":
    [{"id":"0","name":"apple","color":"red"},
    {"id":"1","name":"strawberry","color":"red"},
    {"id":"2","name":"grape","color":"purple"}],
{"Vegetables":
    [{"id":"0","name":"pea","color":"green"},
    {"id":"1","name":"asparagus","color":"green"},
    {"id":"2","name":"corn","color":"yellow"}]
}]
Daddy
  • 9,045
  • 7
  • 69
  • 98
  • This won't help your solution, but you should stop using `mysql_*` functions. They're being deprecated. Instead use [PDO](http://php.net/manual/en/book.pdo.php) (supported as of PHP 5.1) or [mysqli](http://php.net/manual/en/book.mysqli.php) (supported as of PHP 4.1). If you're not sure which one to use, [read this SO article](http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons). – Matt Aug 06 '12 at 20:30
  • 1
    It works for me if I set up a similar array and then `json_encode` it. What does `var_dump($dictionary);` show? How about the same for `$fruits` and `$vegetables`. – drew010 Aug 06 '12 at 20:36
  • Well I checked my httpd error log and I must be doing something wrong. It reported an unexpected $end on line 18. I'll update the post in a bit with the entire file contents, x'ing out the username and password details – Daddy Aug 06 '12 at 20:47
  • I couldn't find the issue, but I re-indented on some whitespace problems and now it works fine. – Daddy Aug 06 '12 at 20:54

0 Answers0