In my farming related Android app user sends crop’s name to PHP webservice and that webservice should return details about that crop.
Here’s the sample structure of database.
Crop_Master:Crop_Id , Crop_Name , Seed_Rate , Fertilizer
Pest: Crop_id , Pest_Name
Now I know about fetchAll() function of PDO and convert it to JSON array if the data is coming from a single table.
Like this: Here data comes from Crop_Master table and works fine.
$query1="select seed_rate,fertilizer_dosage from crop_master where crop_id='$crop_id'";
$res=$db->query($query1);
$output=$res->fetchAll(PDO::FETCH_ASSOC);
print(json_encode($output));
But I don’t know how I can create a single “output” array when the data is coming from multiple tables.
Suppose I want to create a JSON array like this:
[
{
"seed_rate":"value_from_db"
"fertilizer":"value_from_db"
"pests":
[{"pest_name:"value_from_db"}
{"pest_name:"value_from_db"}
.
.
.
]
}
]
Then how can I run multiple queries and make a single output array?
You need to add array element “pests” to the array $output and populate it… How, will depend on the database structure, but likely something like
So, point is, you need to have array of pests as element of your $output array. My $query2 is of course just an example and needs to be adjusted for your database