简体   繁体   中英

Having trouble while encoding json Array in php

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..?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM