I have two different queries which I have to append in same array in form of JSON..
Here is my code from 1st query...
while($row = mysqli_fetch_array($res)) {
array_push($result,array('name'=>$row[0],'photo'=>$row[1],'rollno'=>$row[2],'id'=>$row[3]));
}
Here is my second query push similar as first one.. number of rows is always same as above query
array_push($result,array('status'=>'$status');
After that I'm encoding them like this
echo json_encode(array("result"=>$result));
Here is what I am getting
{"result":[{"name":"Abhishek Singh","photo":"http:\/\/onsitesupport.info\/diary\/photos\/student\/26.png","rollno":"1","id":"26"},
{"status":"status"}]
But I want to result like this
{"result":[{"name":"Abhishek Singh","photo":"http:\/\/onsitesupport.info\/diary\/photos\/student\/26.png","rollno":"1","id":"26","status":"status"}]
I mean status will merge into my every node... how can I achieve this..?
marc_s
760k186 gold badges1.4k silver badges1.5k bronze badges
asked Jan 12, 2017 at 5:35
Abhishek Singh
9,2485 gold badges31 silver badges56 bronze badges
2 Answers 2
Try the below to add status field to each array:
while($row = mysqli_fetch_array($res)){
array_push($result,array('name'=>$row[0],'photo'=>$row[1],'rollno'=>$row[2],'id'=>$row[3]));
}
$res_row = 0;
while($row2 = mysqli_fetch_array($res2)){
$status = $row2[0]; // status value here
$result[$res_row]['status']=$status;
$res_row++;
}
echo json_encode(array("result"=>$result));
answered Jan 12, 2017 at 6:15
mith
1,7001 gold badge10 silver badges13 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Abhishek Singh
a littile bit issue with it ... a status null is adding at start... all nodes are assigned a name like 0,1,2
mith
I am not clear with your issue. can you please explain more... @Abhishek
Abhishek Singh
i am getting this... {"result":{"status":null,"0":{"name":"Abhishek Singh","photo":"http:\/\/onsitesupport.info\/diary\/photos\/student\/26.png","rollno":"1","id":"26","status":"P"}}}
Abhishek Singh
all status are correct but a status was adding at start
Abhishek Singh
sorry it was my mistake of adding a null status.. thanks for you help
Try this please, using temporary arrays that are merged after all your queries are complete:
// Query 1
while($row = mysqli_fetch_array($res)){
$tmpResults[] = $row;
}
// Query 2
$tmpResult2 = array('status'=>'$status');
// Merge Everything
$final = array_merge($tmpResults, $tmpResult2);
// Encode
$json = json_encode($final, TRUE);
Good luck
answered Jan 12, 2017 at 5:59
Ruslan Abuzant
6316 silver badges17 bronze badges
1 Comment
Abhishek Singh
Thanks for you help
lang-php
{"result":{"0":{"name":"Abhishek Singh","photo":"http:\/\/onsitesupport.info\/diary\/photos\/student\/26.png","rollno":"1","id":"26"},"status":"status"}}{"result":[{"name":"Abhishek Singh","photo":"http:\/\/onsitesupport.info\/diary\/photos\/student\/26.png","rollno":"1","id":"26"}]}$result['status'] = $status;then do yourarray_push