Sagar Pawar Sagar Pawar - 5 months ago 18
JSON Question

how to create json array of multiple json object ?

am trying to generate a json array with multiple json objects within it. below is my code with output.

<?php

include_once "/db_connect.php";
$db = new DB_CONNECT();
$head='0';
if(empty($head)){

for($head=1;$head<20;$head++){
if(!empty($head)){

$flatp=mysql_query("SELECT co.id,co.user_id,co.cat_id,co.flatP,hds.HeadName,co.offer_name,u.shop_name,co.cost FROM createdoffers co INNER JOIN categories ct ON ct.id=co.cat_id INNER JOIN
users u ON u.id=co.user_id INNER JOIN heads hds ON hds.id=ct.Head_id
WHERE ct.Head_id='$head' AND ct.id=co.cat_id AND co.user_id=u.id ORDER BY co.flatP DESC LIMIT 1");

if (mysql_num_rows($flatp) >0) {
$response["createdoffers"] = array();
while ($row = mysql_fetch_array($flatp)) {
$recp = array();

$recp["HeadName"]= $row["HeadName"];
$recp["offer_name1"]=$row["offer_name"];
$recp["shop_name1"]=$row['shop_name'];
$recp["cost1"]=$row['cost'];

array_push($response["createdoffers"], $recp);

}
$object=array(array_filter((array)$response));
$res = json_encode($object);
echo trim($res,'[]');
}

}

}
}
?>


and this is my output which has different json objects with different json arrays..

{"createdoffers":[{"HeadName":"Automotives","offer_name1":"flat","shop_name1":"coding spider","cost1":"1300.00"}]}

{"createdoffers":[{"HeadName":"Computer and Electroincs","offer_name1":"happy hour","shop_name1":"coding spider","cost1":"17000.00"}]}

{"createdoffers":[{"HeadName":"Food and Dining","offer_name1":"flat","shop_name1":"codingspider","cost1":"100.00"}]}

what i want is to generate all these three json objects into one json array. am unable to find whats wrong in this ..

Answer
<?php

    include_once "/db_connect.php";
    $db = new DB_CONNECT();
    $head='0';
    $response["createdoffers"] = array();
    if(empty($head)){

    for($head=1;$head<20;$head++){
    if(!empty($head)){

    $flatp=mysql_query("SELECT  co.id,co.user_id,co.cat_id,co.flatP,hds.HeadName,co.offer_name,u.shop_name,co.cost FROM createdoffers co INNER JOIN categories ct ON ct.id=co.cat_id INNER JOIN 
            users u ON u.id=co.user_id INNER JOIN heads hds ON hds.id=ct.Head_id 
            WHERE ct.Head_id='$head' AND ct.id=co.cat_id AND co.user_id=u.id ORDER BY co.flatP DESC LIMIT 1");

        if (mysql_num_rows($flatp) >0) {

        while ($row = mysql_fetch_array($flatp)) {
        $recp = array();

                $recp["HeadName"]= $row["HeadName"];
                $recp["offer_name1"]=$row["offer_name"];
                $recp["shop_name1"]=$row['shop_name'];
                $recp["cost1"]=$row['cost'];

            array_push($response["createdoffers"], $recp);

        }
        $object=array(array_filter((array)$response));  
        $res = json_encode($object);
         echo trim($res,'[]');
        }               

    }

    }
    }
    ?>