简体   繁体   English

在PHP中编码JSON数组时遇到麻烦

[英]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.. 我有两个不同的查询,必须以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 祝好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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