Insert multidimensional array into multidimensional json in PHP - php

I want to insert some data into sub in json data with my data in database
here is my code:
$sql = "SELECT * FROM pharma_data";
$result = mysqli_query($conn, $sql);
$data = array();
while ($row = mysqli_fetch_assoc($result)){
$row_array['id'] = $row['phar_id'];
$row_array['name'] = $row['name'];
$row_array['batch'] = $row['batch_no'];
$row_array['category'] = $row['category'];
$row_array['measurement'] = $row['measurement'];
$row_array['stock'] = $row['stock'];
$row_array['price'] = $row['price'];
$row_array['date'] = $row['date_added'];
$row_array['expiration'] = $row['expiration_date'];
$row_array['type'] = $row['medicin_type'];
$row_array['supplier'] = $row['supplier'];
array_push($data,$row_array);
}
$convert = json_encode($data);
echo $convert;
but the output of my code is:
[{"id":"8","name":"Test Product Name Pharmacy","batch":"Test Product Name Pharmacy","category":"Test Category Pharmacy","measurement":"1mg","stock":"2","price":"15","date":"February 18, 2021, 11:36 am","expiration":"2021-02-18","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"},{"id":"9","name":"Alaxan","batch":"Test user medicine Supplies","category":"Test Category Pharmacy","measurement":"1mg","stock":"66","price":"63.43","date":"February 28, 2021, 4:45 pm","expiration":"2021-02-28","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"},{"id":"10","name":"Medicol","batch":"987","category":"Test Category Pharmacy","measurement":"1mg","stock":"15","price":"123.23","date":"February 28, 2021, 5:42 pm","expiration":"2021-02-28","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"},{"id":"11","name":"test","batch":"test","category":"Test Category Pharmacy","measurement":"213","stock":"32","price":"123.78","date":"February 28, 2021, 6:43 pm","expiration":"2021-02-28","type":"Test Medicine Type Pharmacy","supplier":"Nicole Gonzaga"}]
Want output like this:
{
"total": 800,
"totalNotFiltered": 800,
"rows": [
{
"id": 0,
"name": "Item 0",
"price": "$0"
},
{
"id": 1,
"name": "Item 1",
"price": "$1"
}
]
}
enter image description here

You need to filter out $data before sending it to the response so it means we need a function myFilter to filter the $data elements and we can filter all the elements in the array using array_map(). The total and totalFiltered column seems to give the total number of rows in $data hence the count(). Try the code below:
function myFilter($a) {
$row['id'] = $a['id'];
$row['name'] = $a['name'];
$row['price'] = $a['price'];
return $row;
};
$filterData = array(
'total' => count($data),
'totalNotFiltered' => count($data),
'rows' => array_map("myFilter", $data)
);
$convert = json_encode($filterData);
echo $convert;
Demo code would be here: https://ideone.com/pZCUbG

You need to convert the returned data. Something like:
$data = array();
while ($row = mysqli_fetch_assoc($result)){
$row_array['id'] = $row['phar_id'];
$row_array['name'] = $row['name'];
// $row_array['batch'] = $row['batch_no'];
// $row_array['category'] = $row['category'];
// $row_array['measurement'] = $row['measurement'];
// $row_array['stock'] = $row['stock'];
$row_array['price'] = $row['price'];
// $row_array['date'] = $row['date_added'];
// $row_array['expiration'] = $row['expiration_date'];
// $row_array['type'] = $row['medicin_type'];
// $row_array['supplier'] = $row['supplier'];
$data[] = $row_array; // Same as array_push($data,$row_array);
}
$final_data = array(
'total' => count($data),
'totalNotFiltered' => '',
'rows' => $data
);
$convert = json_encode($final_data);
echo $convert;
Commented out the data that isn't needed in this context (maybe you need it to use elsewhere, not sure. If so just uncomment back)
Not sure with totalNotFiltered as I don't know how you are calculating this. Maybe you can work with that and this gives you an idea to work with.

Related

Convert JSON from MySQL to PHP

So i have this JSON in my MySQL Database
{
"11011001": {
"id": 11011001,
"name": "Test",
"price": 4,
"inCart": 7
}
}
Now i want to work with this data in PHP.
I got the JSON by doing this in PHP:
$sql = "SELECT article FROM test WHERE id = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$aricle = $row["article"];
} else {
echo "Something went wrong";
}
After that i did this which resulted in getting a JSON Array:
$tarray = json_decode($article, TRUE);
What can i do now to get the values from the JSON?
For example i want the value of the price in a variable called $price.
$price = $tarray[11011001]['price'];
Or you can loop through the results if you have many articles
$tarray = json_decode($json,true);
foreach ($tarray as $index => $item)
{
$price[] = $item['price'];
}
var_dump($price);
Assuming you might have a collection of items, you can map the ids to prices with array_column.
<?php
$json =<<<JSON
{
"11011001": {
"id": 11011001,
"name": "Test",
"price": 4,
"inCart": 7
}
}
JSON;
$items = json_decode($json, TRUE);
$ids_prices = array_column($items, 'price', 'id');
var_export($ids_prices);
Output:
array (
11011001 => 4,
)
Only one item, but you don't know the key up front?
if(count($items) === 1) {
$item = array_pop($items);
$price = $item['price'];
}
echo $price;
Output:
4
First you have a sql injection, you must create a prepared query if you have data from users.
$sql = "SELECT article FROM test WHERE id = :id";
$query = $con->prepare($sql);
$query->bindValue(":id", $id);
$query->execute();
$result = $query->fetch();
if ($result) {
// $article will be stdClass if json correct
$article = json_decode($result['article']);
$price = $article->price;
// or $article = json_decode($result['article'], true);
// $price = $article['price'];
}
Just an example

Array json from php is not output in the corect way

I'm trying to make a json output from my db in php with all of users from sql table but i don't know how to do that..i'm new with this.
I want the code to output like this.
[
{
"name": "Maybell",
"avatar": "zeldman/128.jpg",
"data": {
"company": "Alibaba",
"title": "Engineer"
}
}
]
but the my code does the following output and is not ok.
{
"name": "Maybell",
"avatar": "zeldman\/128.jpg",
"company": "alibaba"
"title": "Engineer"
}
Here is the Php code:
<?php
header("Content-type: text/json");
$db = mysqli_connect("localhost","root","","testest");
//MSG
$query = "SELECT * FROM mls_users LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$name = $row['name'];
$avatar = $row['avatar'];
$company= $row['company'];
$title= $row['title'];
}
//Return result to jTable
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['company'] = $company;
$qryResult['title'] = $title;
echo json_encode($qryResult,JSON_PRETTY_PRINT);
mysqli_close($db);
?>
Just change:
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$name = $row['name'];
$avatar = $row['avatar'];
$company= $row['company'];
$title= $row['title'];
}
//Return result to jTable
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['company'] = $company;
$qryResult['title'] = $title;
To:
//Add all records to an array
$qryResult = [];
while ($row = $result->fetch_array()) {
$qryResult[] = [
'name' => $row['name'],
'avatar' => $row['avatar'],
'data' => [
'company' => $row['company'],
'title' => $row['title'],
],
];
}
You can skip setting the intermediate variables and just add onto the $qryResult array directly.
try this:
<?php
header("Content-type: text/json");
$db = mysqli_connect("localhost","root","","testest");
//MSG
$query = "SELECT * FROM mls_users LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$users = array();
while($row = $result->mysqli_fetch_assoc()){
$users[] = [
'name' => $row['name'],
'avatar' => $row['avatar'],
'data' => [
'company' => $row['company'],
'title' => $row['title']
]
]
}
echo json_encode($users,JSON_PRETTY_PRINT);
mysqli_close($db);
?>
I changed fetch_row() to mysqli_fetch_assoc() and then actually made an array with all fetched rows. You kind of wanted to do that i can see that in comments but you didnt. Then just json encode it.
The outlining brackets [ and ] should come automatically when the array has multiple elements in it.
You are almost there, you just need to wrap it in an array and make data an array.
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
// Now make an array to hold data
$data = array();
$data['company'] = $company;
$data['title'] = $title;
// Add data to qryResult
$qryResult['data'] = $data
// Wrap qryResult in array so output will be wrapped in array
$outPutResults = array($qryResult);
echo json_encode($outPutResults,JSON_PRETTY_PRINT);
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['data']['company'] = $company;
$qryResult['data']['title'] = $title;
Try that way. You are asking for a multidimensional-array so you need to set it up as one.

Php Mysql Nested Category Subcategories Json Response

I would like to display categories and subcategories as json response using php mysql. I have three level categories. I am running this query but results not coming as expected. please help me to solve this.
I need json response like below
[{
"id": "1",
"name": "Electronics",
"categorieslevelone": [{
"id": "2",
"name": "Mobiles",
"categoriesleveltwo": [{
"id": "3",
"name": "Samsung",
"parent_id": "2"
}, {
"id": "4",
"name": "Nokia",
"parent_id": "2"
}]
}]
My Code:
header('Content-Type: application/json');
$sql = "select * from category where category_id = 0";
$q = $this->db->conn_id->prepare($sql);
$q->execute();
$json_response = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$row_array = array();
$row_array['id'] = $row['id'];
$row_array['name'] = $row['name'];
$row_array['categorieslevelone'] = array();
$id = $row['id'];
$sqltwo = "select * from category where category_id = ? ";
$r = $this->db->conn_id->prepare($sqltwo);
$r->bindParam(1, $id);
$r->execute();
while ($data = $r->fetch(PDO::FETCH_ASSOC)) {
$id2 = $data['id'];
$row_array['categoriesleveltwo'] = array();
$row_array['categorieslevelone'][] = array(
'id' => $data['id'],
'name' => $data['name'],
);
$sql3 = "select * from category where category_id = ? ";
$s = $this->db->conn_id->prepare($sql3);
$s->bindParam(1, $id2);
$s->execute();
while ($list = $s->fetch(PDO::FETCH_ASSOC)) {
$row_array['categoriesleveltwo'][] = array(
'id' => $list['id'],
'name' => $list['name'],
);
}
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response);
I'm getting a result like you mentioned above. Chenck this out. You have to convert procedural into Object oriented method.
$main_cat = array();
while($row = mysqli_fetch_assoc($query))
{
$query2 = mysqli_query($con,'Select category_id as id,category_name as name from category where parent_id = '.$row['id'].'');
$sub_cat = array();
while($row1 = mysqli_fetch_assoc($query2))
{
$query3 = mysqli_query($con,'Select category_id as id,category_name as name from category where parent_id = '.$row1['id'].'');
$sub_cat2 = array();
while($row2 = mysqli_fetch_assoc($query3))
{
array_push($sub_cat2, $row2);
}
$row1['categoriesleveltwo'] = $sub_cat2;
array_push($sub_cat, $row1);
}
$row['categorieslevelone'] = $sub_cat;
array_push($main_cat, $row);
}
echo json_encode($main_cat);
?>
Hope its will satisfy your requirement
I know this answer is already accepted, but I thought it would make nice code kata.
Code below will build tree structure from adjacency list that you have in db. There are more ways to maintain tree structures, but there's no easy way - all methods involve maintance/code efficiency trade offs.
I used references to build whole tree in one loop regardless of nested nodes number and order in which rows are fetched (would be much easier when parent node was already fetched, but would need extra attention to changes in db) - this way you could order categories alfabetically with db query.
Since it works for any nesting level all children are stored under subcategories key (opposed to categorieslevelxxx), but each subtree might be processed the same way.
...
$link = [];
$data = [];
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$parent = $row['category_id'];
unset($row['category_id']);
empty($link[$id]) or $row += $link[$id];
isset($link[$parent]['subcategories']) or $link[$parent]['subcategories'] = [];
$link[$parent]['subcategories'][] = $row;
$last_idx = count($link[$parent]['subcategories']) - 1;
$link[$id] = & $link[$parent]['subcategories'][$last_idx];
}
$data = $link[1];
unset($link); //tree might be cached here.
$link[1] at the end means we want category 1 and all it's descendants, but you might take any other node. $link[0] would take entire tree when there's more root categories (category_id = 0 in db points to "virtual" root).

Return In JSON Format, PHP

In a project, I have to return user_id, user_age from the database and the return format should be like
user object which contains user_id and user_age
average age of users
count of users
the return format should be in JSON format.
I have created user array and encoded to JSON by using the method
json_encode(user);
my code is like this :
while ($row = mysql_fetch_array($result)) {
$user["id"] = $row["id"];
$user["name"] = ucfirst($row["user_name"]);
$user["date"] = $row["date_of_treatment"];
$user["age"] = $row["age_of_user"];
// push single user into final response array
array_push($response, $user);
$count = $count+1;
$sum_of_age = $sum_of_age+$row["age_of_user"];
}
echo json_encode($response);
I have calculated the average age ($sum_of_age/$count) and count of returned users ($count), but I don't know how to return average age and count of users with the same json response.any help will be appreciated.
You can do like this:
$count=0;
$sum_of_age=0;
$response=array();
$response['users']=array();
while ($row = mysql_fetch_array($result)) {
$user["id"] = $row["id"];
$user["name"] = ucfirst($row["user_name"]);
$user["date"] = $row["date_of_treatment"];
$user["age"] = $row["age_of_user"];
// push single user into final response array
array_push($response['users'], $user);
$count = $count+1;
$sum_of_age = $sum_of_age+$row["age_of_user"];
}
$response['count']=$count;
$response['avg']=$sum_of_age/$count;
echo json_encode($response);
You can try this:
$users = array();
$sum_of_age = 0;
$count = 0;
$users = array();
while ($row = mysql_fetch_array($result))
{
$user["id"] = $row["id"];
$user["name"] = ucfirst($row["user_name"]);
$user["date"] = $row["date_of_treatment"];
$user["age"] = $row["age_of_user"];
// push single user into final response array
$users[] = $user;
$count++;
$sum_of_age += (int) $row["age_of_user"];
}
$response = array(
'users' => $users,
'averageAge' => $sum_of_age/$count,
'count' => $count
);
echo json_encode($response);
This should result in the following json response:
{
"users":[
{ "id" : "1", "name" : "John Doe" , "date" : "2014-03-22 15:20" , "age" : 42 },
{...},
...
],
"averageAge": 42,
"count": 1337
}
<?php
$response = array();
while ($row = mysql_fetch_array($result)) {
$user["id"] = $row["id"];
$user["name"] = ucfirst($row["user_name"]);
$user["date"] = $row["date_of_treatment"];
$user["age"] = $row["age_of_user"];
// push single user into final response array
array_push($response, $user);
$count = $count+1;
$sum_of_age = $sum_of_age+$row["age_of_user"];
}
$response["average_age"] = $sum_of_age / $count;
$response["count"] = $count;
echo json_encode($response);
}
This is the answer, thanks #Amal Murali (commented a link), the link you have provided is working.. :-)

PHP Add to Multidimensional Array using mysql_fetch

I've looked on the web but all I can find is how to echo data from arrays, but I need to add to them. This array is multidimensional so I need to add an array to an array all the time. How do I do this?
Heres the code:
<?php
$data = array(
"contacts" => array(
array(
'id'=> "1",
'catagory'=> "LifeStyle",
'title'=> "Some Cool Title",
'url'=> "http://example.com",
),
)
);
$sql = mysql_query("SELECT * FROM magazines WHERE category = '$cat'");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$cat = $row["category"];
$title = $row["title"];
$url = $row["url"];
// add to array
// array(
// 'id'=> "$id",
// 'catagory'=> "$cat",
// 'title'=> "$title",
// 'url'=> "$url",
// ),
}
mysql_close();
echo json_encode($data);
?>
Just do this...
while($row = mysql_fetch_array($sql)){
$data['contacts'][] = $row;
}
Or this...
while($row = mysql_fetch_array($sql)){
array_push($data['contacts'], $row);
}
Then a print_r will show you your array...
print_r($data);
Instead of doing SELECT * select only the fields you want to push into the array. Something like this
<?php
$sql = mysql_query("SELECT id, category, title, url FROM magazines WHERE category = '$cat'");
while($row = mysql_fetch_array($sql)){
$data['contacts'][] = $row;
}
?>

Categories