我有下面的示例数组:
Array
(
[0] => Array
(
[name] => 'item-1'
[type] => typeA
[ids] => Array(123, 456, 999)
)
[1] => Array
(
[name] => 'item-2'
[type] => typeA
[ids] => Array(555, 4444, 666)
)
[2] => Array
(
[name] => 'item-3'
[type] => typeB
[ids] => null
)
[3] => Array
(
[name] => 'item-4'
[type] => typeB
[ids] => Array(555)
)
)
例如,我想在数组中搜索类型为typeA或id=555的所有条目。我只需要检索名称字段(或者至少检索关键字和名称(。在假设的示例中,搜索将产生项目1、项目2和项目4
我尝试了一些不同的PHP函数。例如
$keys = array_keys(array_column($parent_array, 'type'), 'typeA');
当搜索基于[type]字段时,以上内容适用于检索关键字。但对[ids]不起作用。
有什么建议吗?
我建议使用函数array_filter
来执行搜索
其中的主要元素是具有type or id
逻辑的回调功能
function search_my_array( $array, $type, $id )
{
return array_filter( $array, function( $item ) use ( $type, $id ){
return $item['type'] === $type or ( is_array( $item['ids'] ) and in_array( $id, $item['ids'] ) );
});
}
$array = array(
array('name'=>'item-1','type'=>'typeA','ids'=>array(123,456,789)),
array('name'=>'item-2','type'=>'typeA','ids'=>array(555,444,666)),
array('name'=>'item-3','type'=>'typeB','ids'=>null),
array('name'=>'item-4','type'=>'typeB','ids'=>array(555)),
);
$result = search_my_array( $array, 'typeA', 555 );
结果是完全相同的数组结构,只包含您想要的三个项目,然后您就可以执行array_column
调用
array_column( $result, 'name' );
此外,如果您不总是有type
或ids
字段,请使用isset
加强验证
return ( isset( $item['type'] ) and $item['type'] === $type ) or ( isset( $item['ids'] ) and is_array( $item['ids'] ) and in_array( $id, $item['ids'] ) );