Multi-dimensional Array - mysql_fetch_assoc to Json - php

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);
?>

Related

output an array using PHP

I have the following PHP code:
while($row = mysqli_fetch_array($query))
{
$data = $row['name'];
}
I fetch all the data with the column name "name" in database. How can I output it like this?
["John", "Doe", "Deer"]
You have to make $data as array type variable.
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
print_r($data); // required output
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
print_r($data); // output key wise display like
Array ( [0] => John [1] => Doe ) etc.
But output as you suggestion then just add json_encode()
print_r(json_encode($data)); // output like
["John", "Doe", "Deer"]
$data = [];
while($row = mysqli_fetch_array($query))
{
$data = $row['name'];
}
echo json_encode($data); // or you can use print_r for debugging.
You need to use json_encode() method to your array to be accepted in your jquery. Rearrange the code like following..
$data = array();
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
$new_array = json_encode($data);
echo $new_array; // use 'echo' to print. The json_encode() convert $data array to string.

php - adding data into json

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);

json_encode() error output when i do an while loop to fetch the results in a array

from this php while loop i fetch the results in a array
$rows = array();
$result = mysqli_query($con,"call getProductVariationByID($name)");
//$row = mysqli_fetch_array($result);
while ($row = mysqli_fetch_assoc($result))
{
$rows['Product'][] = $row;
}
echo json_encode($rows, JSON_PRETTY_PRINT);
the result is with this 'null' in the end :
"post_mime_type": "",
"comment_count": "0"
}
]
}null
I bet the function containing this code is echo'd in your main php script.

How can I format my JSON in this way?

I'm trying to output JSON in this format:
[{"name":"venue 1"}, {"name":"venue 2"}, {"name":"venue 3"}]
But it's currently coming out like this:
{"name":"venue 1"}{"name":"venue 2"}{"name":"venue 3"}
Here is my code:
query = "SELECT * FROM venues";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$arr = array(
'name'=> $row['name']
);
print json_encode($arr);
What do I need to change?
Add $arr[] intead of $arr
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$arr[] = array('name'=> $row['name'] );
}
echo json_encode($arr);
Try this:
$arr[] = array(
'name'=> $row['name']
);
Simply make an array like
$array[]["name"]="value1";
$array[]["name"]="value2";
$array[]["name"]="value3";
echo json_encode($array);
you will get the json data as:
[{"name":"value1"},{"name":"value2"},{"name":"value3"}]
which you wants. You have to make the array using looping statements according to your need.

Echo values of arrays?

I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}

Categories