如果没有数据,如何将数组值设置为null
?
以下是我的PHP数组,我是json编码 -
{
"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":[ ]
}
}
}
两个业务中的行数不均匀。如果不存在行,如何将数据设置为null?
$data = array(
'title' => 'Impalz-Marketing',
'type' => 'Business Details',
'version' => '1.0',
'login' => $login_array,
'business' => $business_details_array
);
我试过这个:
$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
}
}
我想要这样的东西 -
{
"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"
}
}
}
答案 0 :(得分:1)
将空值添加到初始数组创建
$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;
}
}
答案 1 :(得分:0)
您可以为'business'设置默认初始数组,并将其值设置为NULL。 然后将数组从DB合并为默认数组。
$defaultBusinessVals = array(
"details" => NULL,
"messages" => NULL,
"offers" => NULL,
"events" => NULL,
"milestone" => NULL,
"products" => NULL,
"brand_exp" => NULL,
"reviews" => NULL,
"agg_reviews" => NULL
);
如果DB数组是这样的:
$dbArr = array(
"details" => "no details",
"messages" => "my msg",
"offers" => 3,
);
然后合并来自DB的数据
$res = $dbArr + $defaultBusinessVals;
或
$res = array_merge($defaultBusinessVals, $dbArr);
结果将是
$res = array(
"details" => "no details",
"messages" => "my msg",
"offers" => 3,
"events" => NULL,
"milestone" => NULL,
"products" => NULL,
"brand_exp" => NULL,
"reviews" => NULL,
"agg_reviews" => NULL
);