在不使用 foreach 循环的情况下搜索比较两个键的多维数组

Search into multidimensional array comparing two keys without using foreach loop

我有这样的数组:

$actions = array(
    array(
        'type'      => 'checkbox',
        'id'        => 'f0',
        'is_active' => 1
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f1',
        'is_active' => 0
    ),
    array(
        'type'      => 'radio',
        'id'        => 'f2',
        'is_active' => 0
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f3',
        'is_active' => 1
    ),
    array(
        'type'      => 'text',
        'id'        => 'f4',
        'is_active' => 1
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f5',
        'is_active' => 0
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f6',
        'is_active' => 1
    )
);

所以我只需要提取类型 = 'checkbox' 和 is_active = 1 的数组 没有任何 "for loop" ..

有什么好的解决办法吗?

您可以将 array_filtercallback 一起使用到 return 只能键入复选框。

$filtered = array_filter($array, function($v){return $v['type'] == 'checkbox' && $v['is_active'] == 1;});

工作示例:- https://3v4l.org/idAR4

编辑@Rakesh Jakhar 的回答

根据问题再添加一个条件

<?php
// Your code here!
$actions = array(
    array(
        'type'      => 'checkbox',
        'id'        => 'f0',
        'is_active' => 1
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f1',
        'is_active' => 0
    ),
    array(
        'type'      => 'radio',
        'id'        => 'f2',
        'is_active' => 0
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f3',
        'is_active' => 1
    ),
    array(
        'type'      => 'text',
        'id'        => 'f4',
        'is_active' => 1
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f5',
        'is_active' => 0
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f6',
        'is_active' => 1
    )
);

$filtered = array_filter($actions, function($v){return $v['type'] == 'checkbox' && $v['is_active']==1 ;});
print_r($filtered);
?>

你也可以起诉array_reduce,Demo

$filtered = array_reduce($array, function($a,$b){
    if($b['type'] == 'checkbox' && $b['is_active'] == 1){
        $a[] = $b;
        return $a;
    }else{
        return $a;
    }},[]);
print_r($filtered);