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 に答える