I am trying to know if the new data can be added to JSON before encoding it?
I am retrieving the data from MySQL database in the following way:
//fetch the data from the database
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$to_encode[] = $row;
}
which gives me this:
[
{
name: "aaa"
},
{
name: "bbb"
}
]
Then I encode it to JSON with:
$array1 = json_encode($to_encode)
I wanted to know if I can add more data into the array before encoding it to make it like this?
[
{
name: "aaa"
age: '5'
},
{
name: "bbb"
age: '5'
}
]
or should I decode the encoded JSON, add the new values and then encode it back?
Simply you can do like this:
//fetch the data from the database
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$to_encode[] = $row;
}
for ($i = 0; $i < count($to_encode); $i++) {
$to_encode[$i]['age'] = '14';
}
$array1 = json_encode($to_encode);
print_r($array1);
Try something like this :
$i=0;
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$to_encode[$i]["name"] = $row;
$to_encode[$i]["age"] = 5;
$i++;
}
$array1 = json_encode($to_encode)
You can push an array to the $row variable, the idea is to build the array before you use json_encode
$to_encode = [];
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$age = array('age'=>5);
array_push($to_encode,$row);
array_push($to_encode,$age);
}
$array = json_encode($to_encode);
Related
I have an array populated using an sql statement in the following manner:
$index = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$bookname[$index] = ($row['Bookname']);
$subjectname[$index] = ($row['SubjectName']);
$index++;
}
When I go to echo json encode the Arrays I get a blank [] when I know it has been populated which is really weird.
Am I doing anything wrong in my context
echo json_encode($Bookname,$SubjectName);
You can use json_encode as like that:
<?php
$index = 0;
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data[$index]['bookname'] = $row['Bookname'];
$data[$index]['subjectname'] = $row['SubjectName'];
$index++;
}
json_encode($data); // encode your array
?>
Try following:
$index = 0;
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data['Bookname'][$index] = $row['Bookname']
$data['SubjectName'][$index] = $row['SubjectName'];
$index++;
}
echo json_encode($data);
You have passed two parameter while calling json_encode function. You batter combine two array in one. Then call the json_encode function like json_encode($combinedArray)
My Mysqli Updated Query and it Outputs this
SELECT milestone.id, milestone.name, milestone.date, milestone.location, milestone.story_body, milestone.short_link, milestone.created_at,
GROUP_CONCAT(images.path) as path , images.update_type
FROM milestone
INNER JOIN images ON milestone.id = images.update_id
WHERE milestone.business_id = '1' && milestone.status = '1' && images.update_type = '3'
GROUP BY milestone.id
How Can I form JSON object using above query?
I've tried below method which doesn't give any result
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
I want something like this -
[
{
"id":"4",
"name":"2nd anniversary",
"date":"2015-12-17",
"location":"Mumbai",
"story_body":"Gzjjs jdk djks jdks jdkd jx djdb djd JD djbd djdj d",
"short_link":"izWfs",
"created_at":"2015-12-11 03:49:52",
"path":
[
{"\/SupportData\/ImpalzB2B\/uploads\/90294930451448437444826.jpg"},
{"\/SupportData\/ImpalzB2B\/uploads\/90294930451449758248579.jpg"}
],
"update_type":"3"
},
{
"id":"7",
"name":"#1styearAnniversary",
"date":"2016-01-20",
"location":"Mumbai",
"story_body":"Bsjsj jdkdk djdkdk dkdkf kdkf dkfj fjfj fjfkjdd djkd",
"short_link":"FHXh0",
"created_at":"2016-01-20 23:10:54",
"path":"\/SupportData\/ImpalzB2B\/uploads\/11453356652175.jpg",
"update_type":"3"
}
]
Note: I know Mysql is not being used in PHP 7. I need to replace it with PDO & Mysqli so please neglect that mistake. I am working on same meanwhile I am facing this query.
You can do this now -
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$temp= explode(',', $row['path']); // explode by ,
if(count($temp) > 1) { // More than one element then assign
$row['path']= $temp;
}
$result_array[] = $row;
}
I'm creating a data.php file which returns a json file to a html file where I fill up a grid with the data from the data.php file.
I need this to be an associative array in the following form:
[
{"CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative"},
{"CompanyName":"Ana Trujillo Emparedados y helados","ContactName":"Ana Trujillo","ContactTitle":"Owner"},
{"CompanyName":"Antonio Moreno Taquera","ContactName":"Antonio Moreno","ContactTitle":"Owner"}
]
Now the problem is, I want this data.php to be sort of generic, which means I don't know the columnnames nor the the amount of columns.
The only way I get this done, is by using a switch statement but this is not ideal (because I can make a number of cases but what if the table has one more column) nor is it very elegant.
I bet this can be done far better, any ideas ?
I tried using array_push() but that doesn't work with associative arrays.
// get columnnames
for ($i = 0; $i < $result->columnCount(); $i++) {
$col = $result->getColumnMeta($i);
$columns[] = $col['name'];
}
// fill up array
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
switch (count($columns);) {
case 1 :
$records[] = array($columns[0] => $row[$columns[0]]);
break;
case 2 :
$records[] = array($columns[0] => $row[$columns[0]], $columns[1] => $row[$columns[1]]);
break;
case 3 :
$records[] = array($columns[0] => $row[$columns[0]], $columns[1] => $row[$columns[1]], $columns[2] => $row[$columns[2]]);
break;
case ... // and so on
}
}
// send data to client
echo json_encode($records);
change the switch code segment with this one
$arr_tmp = array();
for($i = 0; $i < count($columns); $i++)
{
$arr_tmp[$columns[$i]] = $row[$columns[$i]];
}
$records []= $arr_tmp;
You could iterate over the columns:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$values = array();
foreach ($columns as $column) {
values[$column] = $row[$column];
}
records[] = $values;
}
I have used MySql_fetch_assoc and then json_encode
$type = mysql_query("SELECT type_food,category_food,name_food FROM menu ORDER BY type_food,category_food,name_food");
$rows = array();
while($t = mysql_fetch_assoc($type)) {
$rows[]= $t;
}
print json_encode($rows);
which gives me the following results:
{"type_food":"pizza","category_food":"Gourmet","name_food":"pepperoni"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"supreme"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"hawaiian"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"tropical"},
{"type_food":"pizza","category_food":"traditional","name_food":"margherita"},
{"type_food":"pizza","category_food":"traditional","name_food":"vegetarian"}
However I need to make a multidimensional json result like so:
{"pizza": [
{"Gourmet": [
{"pepperoni"},
{"supreme"},
{"hawaiian"},
{"tropical"}]},
{"traditional": [
{"margherita"},
{"vegetarian"}]}
]},
{"etc": [ ... ]}
Is this possible using MySQL associative arrays?
Try this:
$type = mysql_query("SELECT type_food,category_food,name_food FROM menu ORDER BY type_food,category_food,name_food");
$rows = array();
while($t = mysql_fetch_array($type)) {
$rows[$t['type_food']][$t['category_food']][]=$t['name_food'];
}
print json_encode($rows);
<?php
$str='[{"type_food":"pizza", "category_food":"Gourmet", "name_food":"pepperoni"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"supreme"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"hawaiian"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"tropical"},
{"type_food":"pizza","category_food":"traditional","name_food":"margherita"},
{"type_food":"pizza","category_food":"traditional","name_food":"vegetarian"}]';
$rows=json_decode($str,true);
$res=array();
foreach($rows as $row)
{
$res[$row['type_food']][$row['category_food']][]=$row['name_food'];
}
echo json_encode($res);
?>
Basically idea is to grab data from MySQL table and transform it to JSON.
This is how database table looks:
And this how should output be:
[
{"group1":[
{"val":"somevalue"},
{"val":"somevalue"}
]
},
{"group2":[
{"val":"somevalue"},
{"val":"somevalue"}
]
},
{"group3":[
{"val":"somevalue"}
]
}
]
My PHP script looks like this, for now:
$arr = [];
$result = mysql_query("SELECT * FROM thetable WHERE section='sect1'");
while($row = mysql_fetch_array($result))
{
// ???
}
echo json_encode($arr);
My main issue is how to output/sort data in "groups".
Thanks for your help!
try this
while($row = mysql_fetch_array($result))
{
$arr[$row['group']][] = array('val' => $row['value']);
}