【问题标题】:Searching Multi-Dimension Array With Multiple Results搜索具有多个结果的多维数组
【发布时间】:2026-01-06 12:35:02
【问题描述】:

假设我有一个数组,我想搜索一个值应该返回多个结果:

array(2) {
  [0] => array(2) {
    ["id"] => string(2) "1"
    ["custom"] => string(1) "2"
    }
  [1] => array(2) {
    ["id"] => string(2) "2"
    ["custom"] => string(1) "5"
    }
  [2] => array(2) {
    ["id"] => string(2) "3"
    ["custom"] => string(1) "2"
    }
}

我想用value = 2搜索键custom,结果如下:

array(2) {
  [0] => array(2) {
    ["id"] => string(2) "1"
    ["custom"] => string(1) "2"
    }
  [1] => array(2) {
    ["id"] => string(2) "3"
    ["custom"] => string(1) "2"
    }
}

如果不循环数组,这可能吗?是否有这样的类或内置函数?

【问题讨论】:

    标签: php arrays search multidimensional-array


    【解决方案1】:

    你可以使用:

    array_values( array_filter($array, function($item) { return $item['custom'] == 2; }) );

    array_values($array) 用于返回具有连续索引的数组,即从 0、1、2、... 向上。

    【讨论】:

    【解决方案2】:

    array_filter 函数可能就是你想要的。

    $array = [
        [
            'id' => '1',
            'custom' => '2'
        ],
        [
            'id' => '2',
            'custom' => '5'
        ],
        [
            'id' => '3',
            'custom' => '2'
        ]
    ];
    
    $customs = array_filter(
        $array,
        function ($arr) {
            return is_array($arr) && array_key_exists('custom', $arr) && $arr['custom'] === '2';
        }
    );
    

    【讨论】:

    • 注解:没有array_values(),你会得到array(2) { [0] => array(2) { ["id"] => string(2) "1" ["custom"] => string(1) "2" }, [2] => array(2) { ["id"] => string(2) "3" ["custom"] => string(1) "2" } },即返回的数组给出的索引是0和2。但是连续的索引对你来说可能并不重要。
    【解决方案3】:

    您可以通过从数组中取消设置来简单地删除您不想要的值:

    foreach($array as $key => $item) {
        if($item['custom'] !== 2) {
            unset($array[$key]);
        }    
    }
    

    Example


    这是array_values() 的替代方案,但本质上是相同的。

    【讨论】:

      最近更新 更多