我试图过滤一个看起来像这样的数组
$array = array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array(
"otherID" => "theValueIamLookingFor",
"someOtherKey" => "something"
)
);
现在,我正在过滤数据集,其中" otherID"是一定的价值。我知道我可以使用array_filter来过滤" id",但是我不知道如何过滤数组内部数组中的值。
添加WebAPI提供的一些数据(我通过json_decode运行它以在所有这些过滤业务之前创建一个关联数组)
[
{
"id": "b679d716-7cfa-42c4-9394-3abcdged",
"name": "someName",
"actualCloseDate": "9999-12-31T00:00:00+01:00",
"members": [
{
"otherID": "31f27f9e-abcd-1234-aslkdhkj2j4",
"name": "someCompany"
}
],
"competitor": null,
},
{
"id": "c315471f-45678-4as45-457-asli74hjkl",
"name": "someName",
"actualCloseDate": "9999-12-31T00:00:00+01:00",
"members": [
{
"otherID": "askgfas-agskf-as",
"name": "someName"
}
],
"competitor": null,
}, ]
答案 0 :(得分:1)
您可以执行以下操作:
$arr = array(
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "ThisIsNottheValueIamLookingFor",
"someOtherKey" => "something"
)
),
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "theValueIamLookingFor",
"someOtherKey" => "something"
)
),
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "ThisIsNottheValueIamLookingForEither",
"someOtherKey" => "something"
)
),
);
$result = array_filter($arr, function( $v ){
return $v["Members"]["otherID"] == "theValueIamLookingFor";
});
这将导致:
Array
(
[1] => Array
(
[id] => SomeID
[name] => SomeName
[Members] => Array
(
[otherID] => theValueIamLookingFor
[someOtherKey] => something
)
)
)
以下是详细信息的文档:http://php.net/manual/en/function.array-filter.php
在你更新的数组上,数组的结构是不同的。您必须使用$v["members"][0]["otherID"]
获取otherID
请尝试以下代码:
$result = array_filter($arr, function( $v ){
return $v["members"][0]["otherID"] == "theValueIamLookingFor";
});