这里是我要搜索的原始json,以获取特定键的特定值的所有出现
{services:
[
{
servicetypeid: "26",
serviceid: "50",
servicename: "Tax Evasion",
description: "Tax Evasion",
optioncode: { },
inputid: { },
price: { },
categoryidentifier: { }
},
{
servicetypeid: "27",
serviceid: "51",
servicename: "Parking",
description: "Parking Related Payments",
optioncode: { },
inputid: { },
price: { },
categoryidentifier: { }
},
{
servicetypeid: "27",
serviceid: "52",
servicename: "Markets",
description: "Markets Related Payments",
optioncode: { },
inputid: { },
price: { },
categoryidentifier: { }
},
{
servicetypeid: "27",
serviceid: "53",
servicename: "PSV",
description: "Public Service Vehicles",
optioncode: { },
inputid: { },
price: { },
categoryidentifier: { }
},
{
servicetypeid: "5",
serviceid: "54",
servicename: "Vehicle Bill",
description: "Check any Bill Attached to Your Vehicle",
optioncode: "212",
inputid: "216",
price: { },
categoryidentifier: { }
}
]
}
我一直在努力写一个像\的功能
findInjson($ jsonObj,$字段,值)
会回来的 findInjson($ jsonObj, 'servicetypeid', '27');
{services:[
{
servicetypeid: "27",
serviceid: "51",
servicename: "Parking",
description: "Parking Related Payments",
optioncode: { },
inputid: { },
price: { },
categoryidentifier: { }
},
{
servicetypeid: "27",
serviceid: "52",
servicename: "Markets",
description: "Markets Related Payments",
optioncode: { },
inputid: { },
price: { },
categoryidentifier: { }
},
{
servicetypeid: "27",
serviceid: "53",
servicename: "PSV",
description: "Public Service Vehicles",
optioncode: { },
inputid: { },
price: { },
categoryidentifier: { }
}
]
}
答案 0 :(得分:0)
要搜索该数组中的那些键,您可以执行以下操作:
解决 PHP 5.3
function findinjson($jsonContent, $field, $value)
{
$jsonObject = json_decode($jsonContent, true);
// This is to search inside the first array, which only has one element
$searchArray = $jsonObject['services'];
// Array filter applies the function given as a parameter to each element of $searchArray
$filteredArray = array_filter($searchArray, function($element) use ($field, $value) {
return array_key_exists($field, $element) && $element[$field] == $value;
});
// Output the data the same way it was given, but filtered.
return json_encode(array('services' => $filteredArray));
}
希望这就够了。如果您需要 PHP 5.2 解决方案,您可以通过迭代$filteredArray
而不是使用数组过滤器来构建$searchArray
,并且仅添加$filteredArray
通过条件。因此,对array_filter
的调用将替换为以下代码:
$filteredArray = array();
foreach ($searchArray as $element) {
if (array_key_exists($field, $element) && $element[$field] == $value) {
$filteredArray[] = $element;
}
}