项目需求
- 一组数据格式需要判断是否存在键名name,如果存在,则直接输出;如果不存在,直接过滤掉;
- 使用
array_key_exists
函数;
数据格式
{ "err": "", "res": "", "data": [ { "name": "CVR06", "cpu": 13, "ddr": 61, "disk": 84, "wlan": 24, "storage": 0, "status": { "cpu": [ "正常运行" ], "disk": "正常运行", "wlan": "正常运行", "ddr": [ "正常运行" ], "storage": "正常运行" } }, { "name": "CVR03", "cpu": 15, "ddr": 44, "disk": 77, "wlan": 43, "storage": 0, "status": { "wlan": "正常运行", "ddr": [ "正常运行" ], "cpu": [ "正常运行" ], "disk": "正常运行", "storage": "正常运行" } }, { "name": "CVR04", "cpu": 14, "ddr": 45, "disk": 77, "wlan": 33, "storage": 0, "status": { "wlan": "正常运行", "ddr": [ "正常运行" ], "cpu": [ "正常运行" ], "disk": "正常运行", "storage": "正常运行" } }, { "name": "CVR07", "cpu": 13, "ddr": 61, "disk": 84, "wlan": 30, "storage": 0, "status": { "cpu": [ "正常运行" ], "disk": "正常运行", "wlan": "正常运行", "ddr": [ "正常运行" ], "storage": "正常运行" } }, { "name": "CVR08", "cpu": 11, "ddr": 56, "disk": 84, "wlan": 26, "storage": 0, "status": { "wlan": "正常运行", "disk": "正常运行", "cpu": [ "正常运行" ], "ddr": [ "正常运行" ], "storage": "正常运行" } }, { "name": "CVR09", "cpu": 12, "ddr": 57, "disk": 84, "wlan": 26, "storage": 0, "status": { "wlan": "正常运行", "disk": "正常运行", "cpu": [ "正常运行" ], "ddr": [ "正常运行" ], "storage": "正常运行" } }, { "cpu": 0, "ddr": 0, "disk": 0, "wlan": 0, "storage": 0, "status": { "cpu": "正常运行", "ddr": "正常运行", "disk": "正常运行", "wlan": "正常运行", "storage": "正常运行" } }, { "cpu": 0, "ddr": 0, "disk": 0, "wlan": 0, "storage": 0, "status": { "cpu": "正常运行", "ddr": "正常运行", "disk": "正常运行", "wlan": "正常运行", "storage": "正常运行" } }, { "cpu": 0, "ddr": 0, "disk": 0, "wlan": 0, "storage": 0, "status": { "cpu": "正常运行", "ddr": "正常运行", "disk": "正常运行", "wlan": "正常运行", "storage": "正常运行" } }, { "cpu": 0, "ddr": 0, "disk": 0, "wlan": 0, "storage": 0, "status": { "cpu": "正常运行", "ddr": "正常运行", "disk": "正常运行", "wlan": "正常运行", "storage": "正常运行" } }, { "cpu": 0, "ddr": 0, "disk": 0, "wlan": 0, "storage": 0, "status": { "cpu": "正常运行", "ddr": "正常运行", "disk": "正常运行", "wlan": "正常运行", "storage": "正常运行" } }, { "cpu": 0, "ddr": 0, "disk": 0, "wlan": 0, "storage": 0, "status": { "cpu": "正常运行", "ddr": "正常运行", "disk": "正常运行", "wlan": "正常运行", "storage": "正常运行" } }, { "name": "一卡通服务器", "cpu": 51, "ddr": 73, "disk": 19, "wlan": 0, "storage": 72, "status": { "cpu": [ "正常运行" ], "disk": "正常运行", "storage": [ "正常运行" ], "ddr": [ "正常运行" ], "wlan": "正常运行" } } ] }
解决方案
//读取JSON数据; $data = file_get_contents("data.json"); //数组解码; $arr = json_decode($data, true); //判断并过滤数组 foreach ($arr["data"] AS $k => $v) { if (array_key_exists("name", $arr["data"][$k])) { echo $v["name"]; } } //重新组建数组并输出; $listArr = array(); foreach ($arr["data"] AS $k => $v) { if (array_key_exists("name", $arr["data"][$k])) { $listArr[] = $v; } }
lockdatav Done !