New to php. I am trying to send JSON data to front end in name-value pair. I tried an example which I got here The following is my code fragment which sends the data in JSO
$list needs to be an array, and you can just push items to it like in this code:
$list = array();
while($stmt->fetch()){
$list[] = array('id' => $fid, 'name' => $fname);
}
$stmt->free_result();
$stmt->close();
echo json_encode($list);
You could also use the method fetch_all() to get all rows at once, instead of iterating with a loop. Although in this example you'd get all fields that you've selected, instead of just id and name.
$list = $stmt->fetch_all();
$stmt->free_result();
$stmt->close();
echo json_encode($list);
try creating an array of objects
$list = array();
while($stmt->fetch()) {
// create an object
$datum=new stdClass();
$datum->id=$fid;
$datum->name=$fname;
$list[] = $datum;
}
$stmt->free_result();
$stmt->close();
echo json_encode($list);
Let's suppose we have this file structure without specific Objects inside :
{
"Subjects" : []
}
//Get your Json file and decode it
$json = file_get_contents('CdStore/Pagetest.json');
$json_data = json_decode($json,true);
//Specifiy your Objects like this
$NewArray= array( 'Mathematics' => array(),'Physics' => array());
//Push the new Objects
array_push($json_data['Pagess'],$NewArray);
//Then encode to json
$array = json_encode($json_data);
//If you want to get the preview before saving
print_r($array);
//Save your file
file_put_contents('CdStore/Pagetest.json', json_encode($json_data));
As result you have :
{"Subjects":
[
{
"Mathematics":[],
"Physics":[]
}
]
}
See if this works for you:
$n = 0;
while($stmt->fetch()){
$list[$n] = array('id' => $fid, 'name' => $fname);
$n++;
}
$stmt->free_result();
$stmt->close();
echo json_encode($list);
You were overwriting the $list
multiple times with an array.
Your list array is only storing 1 row. Try this:
while ($stmt->fetch()) {
$list[] = array('id' => $fid, 'name' => $fname);
}
Hope this helps!
You should try pushing each object at the end of array like adding to a stack using array_push
(the equivalent of $array[] = $data
, but makes it more readable to you).
$list=array(); //instantiate the array
while($stmt->fetch()){
$data = new stdClass(); // create a new object
$data->id=$fid;
$data->name=$fname;
array_push($list,$data); // push object to stack array
}
$stmt->free_result();
$stmt->close();
echo json_encode($list);