SA__
SA__

Reputation: 1862

Constructing json array inside while loop

Here is my Query to construct dynamic json

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

Here is the Expected output and actual output ....

The first one is the console of the data that is expected (i put console as static) the actual output is the second one.

Here is the variable used to console the static output.

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 }
    }]
}

How can i make the shapes as array like the first one ?

enter image description here

Note :

This questions is the continuation of this one

Upvotes: 4

Views: 1701

Answers (1)

Suchit kumar
Suchit kumar

Reputation: 11859

Try this:

$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'], 'y'=> $row['y'], 'width' => $row['width'], 'height'=>$row['height']) ); 
$i++; 
} 
echo json_encode($result);

Upvotes: 1

Related Questions