我跟随json
{
"id": 81,
"bank_id": 2,
"service_id": 1,
"created_at": "2014-12-05 06:40:23",
"updated_at": "2014-12-05 06:40:23",
"alias": "remit",
"alias_burmese": "remit",
"reputation": null,
"contact": null,
"service": null
},
{
"id": 82,
"bank_id": 2,
"service_id": 2,
"created_at": "2014-12-05 06:40:24",
"updated_at": "2014-12-05 06:40:24",
"alias": "international remit",
"alias_burmese": "international remit",
"reputation": {
"id": 1,
"bank_service_id": 82,
"reputation_points": "-2",
"created_at": "2014-12-25 10:08:40",
"updated_at": "2014-12-25 10:08:40"
},
"contact": null,
"service": {
"id": 2,
"parent_id": 1,
"service": "International Remittance",
"service_burmese": "International Remittance",
"is_active": "1",
"created_at": "2014-09-12 08:31:57",
"updated_at": "2014-09-12 08:31:57",
"service_order": 1
}
}
我想忽略条目将为NULL服务..所以我的条目将如下所示
{
"id": 82,
"bank_id": 2,
"service_id": 2,
"created_at": "2014-12-05 06:40:24",
"updated_at": "2014-12-05 06:40:24",
"alias": "international remit",
"alias_burmese": "international remit",
"reputation": {
"id": 1,
"bank_service_id": 82,
"reputation_points": "-2",
"created_at": "2014-12-25 10:08:40",
"updated_at": "2014-12-25 10:08:40"
},
"contact": null,
"service": {
"id": 2,
"parent_id": 1,
"service": "International Remittance",
"service_burmese": "International Remittance",
"is_active": "1",
"created_at": "2014-09-12 08:31:57",
"updated_at": "2014-09-12 08:31:57",
"service_order": 1
}
}
什么是最好的选择..我试图将json转换为数组并尝试使用array_filter进行过滤?
答案 0 :(得分:1)
是的,您可以使用array_filter,json_decode和json_encode来实现这一目标。请注意,在用数组表示法[]
包装它之前,您的JSON示例无效。
<?php
// callback function for array_filter
function filterNullService($obj) {
if(!is_null($obj->service)){
return $obj;
}
}
$json = '[{
"id": 81,
"bank_id": 2,
"service_id": 1,
"created_at": "2014-12-05 06:40:23",
"updated_at": "2014-12-05 06:40:23",
"alias": "remit",
"alias_burmese": "remit",
"reputation": null,
"contact": null,
"service": null
},
{
"id": 82,
"bank_id": 2,
"service_id": 2,
"created_at": "2014-12-05 06:40:24",
"updated_at": "2014-12-05 06:40:24",
"alias": "international remit",
"alias_burmese": "international remit",
"reputation": {
"id": 1,
"bank_service_id": 82,
"reputation_points": "-2",
"created_at": "2014-12-25 10:08:40",
"updated_at": "2014-12-25 10:08:40"
},
"contact": null,
"service": {
"id": 2,
"parent_id": 1,
"service": "International Remittance",
"service_burmese": "International Remittance",
"is_active": "1",
"created_at": "2014-09-12 08:31:57",
"updated_at": "2014-09-12 08:31:57",
"service_order": 1
}
}]';
$array = json_decode($json);
$result = array_filter($array, "filterNullService");
$jsonResult = json_encode($result);
echo "<pre>";
print_r($result);
print_r($jsonResult);
echo "</pre>";
答案 1 :(得分:0)
是的,您需要使用json_decode函数将第二个参数作为true
将JSON字符串转换为数组。然后使用array_filter过滤数组,并使用json_encode
如果您需要示例代码,请与我们联系。