php – 在循环中构造json数组

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 在循环中构造json数组脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我构建动态json的Query

$Query = "SELECT url as src,notes as text,`x-axis` as x,`y-axis` as y,width as width,height as height From annotate where `url` ='".$url."' limIT 0,10 ";  
$Result = $Connection->query($Query); 
$Data = $Result->fetch_assoc(); 
$result=array(); 
$i=0; 
while($row = $Result->fetch_assoc()){ 
$result[$i]['src']=$row['src']; 
$result[$i]['text']=$row['text']; 
$result[$i]['Shapes']['tyPE']= 'rect';
$result[$i]['shapes']['geometry'] =array('x' => $row['x'],'y'=> $row['y'],'width' => $row['width'],'height'=>$row['height'] ); 
$i++; 
} 
echo json_encode($result);

这是预期的输出和实际输出….

一个是预期的数据控制台(我将控制台设置为静态)实际输出是第二个.

这是用于控制静态输出的变量.

VAR my = {
    src : 'http://192.168.1.58/annotate/drive/image/<?PHP echo $_GET['file']?>',text : 'Suresh and Gopinath....',shapes : [{
        type : 'rect',geometry : { x : 0.1825726141078838,y: 0.23756906077348067,width : 0.11602209944751381,height: 0.11618257261410789 }
    }]
}

怎样才能像第一个那样将形状作为数组?

php – 在循环中构造json数组

注意 :

这个问题是this one的延续

解决方法

试试这个:

$Result = $Connection->query($Query); 
$result=array(); 
$i=0; 
while($row = $Result->fetch_assoc()){ 
$result[$i]['src']=$row['src']; 
$result[$i]['text']=$row['text']; 

$result[$i]['shapes'][]=array('type'=>'rect','geometry'=>array('x' => $row['x'],'height'=>$row['height']) ); 
$i++; 
} 
echo json_encode($result);

脚本宝典总结

以上是脚本宝典为你收集整理的php – 在循环中构造json数组全部内容,希望文章能够帮你解决php – 在循环中构造json数组所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。