我有一个读取JSON文件的php代码。以下JSON示例的一部分:
"Main": [{
"count": 7,
"coordinates": [89,77],
"description": "Office",
},{
"count": 8,
"coordinates": [123,111],
"description": "Warehouse",
}]
并且我正在尝试对PHP进行编码,以仅获取描述者(包括)的信息(计数,坐标,描述)Warehouse
。下面的PHP示例
$validcriteria = array("Warehouse", "Parking_lot");
我如何执行if语句来首先检查有效条件中是否包含“描述”。我尝试了下面的代码,但似乎无法正常工作。
$JSONFile = json_decode($uploadedJSONFile, false);
foreach ($JSONFile as $key => $value)
{
if (in_array($key['description'] , $validcriteria))
{
#more codes here
}
}
我的PHP代码一直有效,除了当我尝试添加$key['description']
尝试并首先检查描述是否有效时。上面的代码经过重构,可以删除敏感信息,但我希望您对我正在尝试做的事情有所了解。
尝试了解已解析的JSON字符串的结构时,请从开始print_r($JSONFile);
检查其内容。在您的情况下,您会发现有一个'Main'
包含子数组数组的外键。您将需要遍历该外部数组。
// Set $assoc to TRUE rather than FALSE
// otherwise, you'll get an object back
$JSONFile = json_decode($uploadedJSONFile, TRUE);
foreach ($JSONFile['Main'] as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value['description'], $validcriteria))
{
// Do what you need to with it...
}
}
注意:如果您希望继续将$assoc
参数设置为false
in json_decode()
,请检查结构以了解对象的布局,并使用->
运算符代替数组键。
$JSONFile = json_decode($uploadedJSONFile, FALSE);
foreach ($JSONFile->Main as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value->description, $validcriteria))
{
// Do what you need to with it...
}
}
您可能还考虑使用array_filter()
做测试:
$included_subarrays = array_filter($JSONFile['Main'], function($a) use ($validcriteria) {
return in_array($a['description'], $validcriteria);
});
// $included_subarrays is now an array of only those from the JSON structure
// which were in $validcriteria
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句