0

这是我想要搜索以获取特定键的特定值的所有出现的原始 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,$field,value)

这将返回 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: { }
}
]
}
4

1 回答 1

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;
    }
}
于 2012-07-31T11:12:14.053 回答