Nehil Mistry Nehil Mistry - 7 months ago 11
PHP Question

PHP array set null value

How can I set array value to

null
if no data exist?

Following is my array from PHP and I am json encoding -

{
"title":"Impalz-Marketing",
"type":"Business Details",
"version":"1.0",
"login":[ ],
"business":{
"1":{
"details":{ },
"messages":[ ],
"offers":[ ],
"events":[ ],
"milestone":[ ],
"products":[ ],
"brand_exp":[ ],
"reviews":[ ],
"agg_reviews":{ }
},
"168":{
"details":{ },
"messages":[ ],
"products":[ ]
}
}
}


Number of rows are uneven in both business. How can I set data to null if no row exist?

$data = array(
'title' => 'Impalz-Marketing',
'type' => 'Business Details',
'version' => '1.0',
'login' => $login_array,
'business' => $business_details_array
);


I've tried this:

$business_details_array = array();
while($row = mysql_fetch_assoc($biz_list))
{
$business_details_array[$row['id']]['details'] = $row;
}

while($row = mysql_fetch_assoc($biz_milestone))
{
if(!empty($row['id'])){
$temp= explode(',', $row['path']);
if(count($temp) > 1) {
$row['path']= $temp;
}
$business_details_array[$row['business_id']]['milestone'][] = $row;
}else{
$business_details_array[]['milestone'][] = null; // since no data exist their wont be any business_id
}
}


I want something like this -

{
"title":"Impalz-Marketing",
"type":"Business Details",
"version":"1.0",
"login":[ ],
"business":{
"1":{
"details":{ },
"messages":[ ],
"offers":[ ],
"events":[ ],
"milestone":[ ],
"products":[ ],
"brand_exp":[ ],
"reviews":[ ],
"agg_reviews":{ }
},
"168":{
"details":{ },
"messages":[ ],
"offers": "null",
"events": "null",
"milestone": "null",
"products":[ ],
"brand_exp": "null",
"reviews": "null",
"agg_reviews": "null"
}
}
}

Answer

Add nulls to your initial array creation

$business_details_array = array();
while($row = mysql_fetch_assoc($biz_list))
{
    $business_details_array[$row['id']]['details'] = $row;
    $business_details_array[$row['id']]['milestone'] = null;
    $business_details_array[$row['id']]['products'] = null;
    $business_details_array[$row['id']]['messages'] = null;
}

    while($row = mysql_fetch_assoc($biz_milestone))
    {
        if(!empty($row['id'])){
            $temp= explode(',', $row['path']);
            if(count($temp) > 1) {
                $row['path']= $temp;
            }
            $business_details_array[$row['business_id']]['milestone'][] = $row;
        }      
    }   
Comments