add array in each object of array in php - php

I am new to PHP. I wanted to add array in each object of array. It is array inside array and each array object contains a array. I also search on internet I didn't find anything related to this.
Here is my desire json
[{
"id":1,
"name":"Grey",
"list":[
{
"id":1,
"name":"60 X 60 ABC"
},
{
"id":2,
"name":"40 X 40 PQR"
},
{
"id":3,
"name":"45 X 45 XYZ"
}
]
},
{
"id":2,
"name":"Yarn",
"list":[
{
"id":4,
"name":"YARN ABC"
},
{
"id":5,
"name":"YARN XYZ"
}
]
}]
All this data is filled from mysql database.
Here is my php code
$sql = "select * from tblType";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($rows = $result->fetch_assoc()) {
$obj = new stdClass;
$obj->id = $rows["id"];
$obj->name = $rows["name"];
$obj->list = $array2;
$sql2 = "select * from tblQuality where typeId = $obj->id";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$obj2 = new stdClass;
$obj2->id = $row["id"];
$obj2->name = $row["name"];
array_push($array2, $obj2);
}
}
array_push($array, $obj);
}
}
echo json_encode($array);
mysqli_close($conn);
I don't know how to add array inside array. Please help.

try this:
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$sql = "select * from tblType";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($rows = $result->fetch_assoc()) {
$obj = new stdClass;
$obj->id = $rows["id"];
$obj->name = $rows["name"];
$obj->list = array();
$sql2 = "select * from tblQuality where typeId = $obj->id";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$obj2 = new stdClass;
$obj2->id = $row["id"];
$obj2->name = $row["name"];
array_push( $obj->list, $obj2);
}
}
array_push($array, $obj);
}
}
echo json_encode($array);
mysqli_close($conn);

Here you are:
$sql = "select * from tblType";
$result = $conn->query($sql);
$results = [];
if ($result->num_rows > 0) {
while($rows = $result->fetch_assoc()) {
$item = [];
$item['id'] = $rows['id']
$item['name'] = $rows['name'];
$item['list'] = [];
$sql2 = "select * from tblQuality where typeId = " . $rows['id'];
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$item['list'][] = [
'id' => $row['id'],
'name' => $row['name']
]
}
}
$results[] = $item
}
}
echo json_encode($results);
mysqli_close($conn);
Hint: don't use stdClass objects as arrays. They're not meant for that.

Related

JSON output returns null using PHP ajax

When I view the record from the database, the result is displayed as null.
This is what I tried so far:
<?php
include("db.php");
$fetchqry = "SELECT mid, planid, paid_date, expire_date FROM payment";
$result = mysqli_query($conn, $fetchqry);
$num = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$mid = $row['mid'];
$planid = $row['planid'];
$date1 = $row['expire_date'];
if (strtotime(date("Y/m/d")) < strtotime($date1))
{
$status = "Active";
}
else
{
$status = "Expired";
}
}
echo json_encode($row);
?>
Add the values you read from the DB to an array, then encode that.
$output = [];
$today = strtotime(date("Y/m/d"));
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$mid = $row['mid'];
$planid = $row['planid'];
$date1 = $row['expire_date'];
if($today < strtotime($date1))
{
$status = "Active";
}
else
{
$status = "Expired";
}
$output[] = ['mid' => $mid, 'planid' => $planid, 'status' => $status];
}
echo json_encode($output);

PHP: Array to string conversion when retrieving outside function

Good day!
I have a problem here that I can't solve (last 5hrs).
here's my codes:
include 'assets\function\retrieveFunction.php';
$loadGradProgram = array();
$x = count(getCourseInfo());
for($i=0;$i<=$x;$i++){
$loadGradProgram[$i] = getCourseInfo();
}
echo $loadGradProgram[0];
getCourseInfo function
Solution 1:
function getCourseInfo(){
$getInfo = array();
include 'assets\database\connect.php';
$i = 0;
$x = 0;
$sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
$sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i] = $row;
$i++;
}
return $getInfo;
}
}
Result: Array to string conversion
Solution 2:
function getCourseInfo(){
$getInfo = array();
$loadInfo = array();
include 'assets\database\connect.php';
$i = 0;
$x = 0;
$sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
$sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i] = $row;
$i++;
}
$conn->close();
for($x,$x<=$i;$x++;){
$loadInfo[] = implode(',', $getInfo[$x]);
}
return $loadInfo;
}
}
Result: Still the same
and this line causing error: echo $loadGradProgram[0];
I use echo just to see if the query is working.
if you want a multi-dimmentional array like in w3c documentation, you do it like this :
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i][] = $row['courseID'];
$getInfo[$i][] = $row['courseCode'];
...
$i++;
}
return $getInfo;
then, if you want to diplay an information in the array you can do a foreach loop or a for loop like :
foreach($loadGradProgram as $key => $value) // here the key is useless
{
echo $value[0];
echo $value[1];
}
or directly like this :
echo $loadGradProgram[0][0];
echo $loadGradProgram[0][1];
echo $loadGradProgram[1][0];

How to output like this in php

I want to achieve this output in php.
[
{
"id": 1388534400000,
"author": "Pete Hunt",
"text": "Hey there!"
},
{
"id": 1420070400000,
"author": "Paul O’Shannessy",
"text": "React is *great*!"
}
]
I have a while loop in my backend below.
$pull = "SELECT * FROM mydb";
$result = $con->query($pull);
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$json['id'] = $row['id'];
$json['author'] = $row['author'];
$json['text'] = $row['text'];
}
echo json_encode($json);
It only returns the last row in the database, and I want to display them all.
Thank you.
If your $row contains only these three fields from database then use below code otherwise #govindkr13 answer
$pull = "SELECT * FROM mydb";
$result = $con->query($pull);
$json = [];
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$json[] = $row;
}
echo json_encode($json);
You are simply overwriting your $json array every time. Try this:
$i=0;
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$json[$i]['id'] = $row['id'];
$json[$i]['author'] = $row['author'];
$json[$i]['text'] = $row['text'];
$i++;
}
echo json_encode($json);
use this
$pull = "SELECT * FROM mydb";
$result = $con->query($pull);
$final = [];
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$json['id'] = $row['id'];
$json['author'] = $row['author'];
$json['text'] = $row['text'];
$final[] = $json;
}
echo json_encode($final);
Maybe this can help.
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$json[$row['id']]['author'] = $row['author'];
$json[$row['id']]['text'] = $row['text'];
}
$i=0;
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$json[$i]['id'] = $row['id'];
$json[$i]['author'] = $row['author'];
$json[$i]['text'] = $row['text'];
$i++;
}
echo json_encode($json);
try this
$count=0;
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$json[$count]['id'] = $row['id'];
$json[$count]['author'] = $row['author'];
$json[$count]['text'] = $row['text'];
$count++;
}
echo json_encode($json);

Form json using php json_encode failed

By using below code
$data = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data['title'] = $row['title'];
$data['name'] = $row['name'];
}
}
echo json_encode($data);
I got 1 result, I can get full result if I do $data[] = $row['title'], but I want to make the result like this
{'title' : ['title 1','title 2'], 'name':['John','Amy']}
You are overwriting the title in each loop iteration. You need to accumulate all the titles and then set it in your data array.
$data = array();
$sql = "SELECT title FROM mainlist";
$result = $db->query($sql);
$titles = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
}
}
$data['title'] = $titles;
echo json_encode($data);
The easiest away is probably this:
$rows = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
}
echo json_encode($rows);
you could achieve by using group_concat on each of the columns in your query. That way you do not need to loop the result again and add column etc...
$sql = "SELECT group_concat(title) as title,group_concat(name) as name FROM list";
$result = $db->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Try this:
$titles = array();
$names = array();
$sql = "SELECT title,name FROM mainlist";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
$names[] = $row['name'];
}
}
echo json_encode(array("title" => $titles, "name" => $names));
UPDATE
Updated my code to let you manage an undefined number of columns as result
$out = array();
$sql = "SELECT * FROM wp_cineteca";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$keys = array_keys($row);
for ($i = 0; $i < count($row); $i++) {
$out[$keys[$i]][] = $row[$i];
}
}
}
echo json_encode($out);

How can I display this MySQL loop in a line Highchart?

I'm trying to display this query output in a Highchart (line). I’dlike to know how to input this MySQL loop into the Highchart.
<?php
$qu = "SELECT *,COUNT(url) FROM clicks WHERE url='aaaa' GROUP BY date";
$result = mysql_query($qu) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$hits = $row['COUNT(url)'];
$date = $row['date'];
}?>
Maybe this gives you some idea:
$label = array();
while($row = mysql_fetch_array($result))
{
$label[] = $row["date"];
$data_count[] = (float)$row["COUNT(url)"];
}
$series = array();
$series[] = array("name"=> 'total', "color" => "#4572a7", "data" => $data_count);
$data = array();
$data["chart"]["renderTo"] = "report";
$data["chart"]["defaultSeriesType"] = "column";
$data["title"]["text"] = "Some Title Here";
$data["series"] = $series;
$data["xAxis"]["categories"] = $label;
$data["yAxis"]["allowDecimals"] = true;
header('Content-Type: application/json; charset: utf-8;');
echo json_encode($data);

Categories