I am very very new at PHP and I don’t even know JSON. Also, I couldn’t know how to express it in the question. My question is;
I need to make a JSON data with PHP with the data from database. So what my expected output is like;
{ "canFireAPICalls": true, "ads": { "servers": [ { "type": "OpenX", "apiAddress": "http://openx.openvideoads.org/openx/www/delivery/fc.php", } ], "schedule": [ { "zone": "5", "position": "pre-roll" }, { "zone": "33", "width": 450, "height": 50, "startTime": "00:00:05", "duration": "15" } ], } }
What I wrote in PHP is;
while ($doZones->fetch() && $row = $doZones->toArray()) {
$row_array['zone'] = $row['zoneid'];
$row_array['position'] = $row['delivery'];
if($row['delivery'] == 0 || $row['delivery'] == 1 || $row['delivery'] == 4 ){
$row_array['width'] = $row['width'];
$row_array['height'] = $row['height'];
}
array_push($return_arr,$row_array);
}
$resultJSON .=json_encode($return_arr);
And my output is
{ "canFireAPICalls": true, "ads": { "servers": [ { "type": "OpenX", "apiAddress": "http://openx.openvideoads.org/openx/www/delivery/fc.php", } ], "schedule":[{"zone":"3","position":"6"},{"zone":"2","position":"6"},{"zone":"4","position":"6"},{"zone":"5","position":"6"},{"zone":"6","position":"1","width":"468","height":"60"},{"zone":"7","position":"6","width":"468","height":"60"},{"zone":"8","position":"0","width":"120","height":"600"},{"zone":"9","position":"7","width":"120","height":"600"},{"zone":"10","position":"0","width":"120","height":"600"},{"zone":"11","position":"0","width":"728","height":"90"},{"zone":"12","position":"0","width":"120","height":"90"},{"zone":"13","position":"1","width":"468","height":"60"},{"zone":"14","position":"3","width":"468","height":"60"},{"zone":"15","position":"1","width":"560","height":"40"},{"zone":"16","position":"4","width":"468","height":"60"},{"zone":"17","position":"6","width":"468","height":"60"},{"zone":"18","position":"6","width":"468","height":"60"},{"zone":"19","position":"7","width":"468","height":"60"}] } }
If you noticed, even there shouldn’t be width and height, there is. I only want the width and height when $row[‘delivery’] is 0,1 or 4. But, once it finds a value 0,1 or 4, then even if the next row is not 0,1 or 4, it prints width and height. Is there a way to fix this? I don’t know any JSON and just started with PHP. Right now, I don’t care about the missing tags like duration or writing pre-roll. I will take care of them after I fix this.
The problem is in your php. You don’t reset the values of your array
$row_array, so the first time the condition is true, the values of height and width are kept in the array.You can fix it this way :