首页 > 解决方案 > Why does search for matching value in multi dimensional array not return a result?

问题描述

I have a multi dimensional array where I want to retrieve the key of each element that matches '116234':

$test = Array
(
    [8708] => Array
    (
        [ref_id] => 93939
    )

    [8709] => Array
    (
        [ref_id] => 116234
    )

    [8710] => Array
    (
        [ref_id] => 116234
    )
)

In that case the desired keys are: 8709, 8710.

Somehow the filter function does not work:

$data['attr'][8] = '116234';
$filtered = array_filter($test, function($v) { return $v['ref_id'] == $data['attr'][8]; });
print_r($filtered);

response: 
Array
(
)

According to an answer within another question at SO this should work.

Is this somehow wrong, or does the filter function rely on a certain PHP version?

标签: phparrays

解决方案


您的代码不起作用,因为$data不在您的匿名函数的范围内。如果您启用了 PHP 错误报告,您将看到 3 条如下错误消息:

注意:未定义变量:/in/RNpEd 中 nnn 行的数据

你需要像这样重写你的代码(注意use ($data)匿名函数的定义):

$test = array('8708' => array('ref_id' => '93939'), '8709' => array('ref_id' => '116234'), '8710' => array('ref_id' => '116234'));
$data['attr'][8] = '116234';
$filtered = array_filter($test, function($v) use($data) { return $v['ref_id'] == $data['attr'][8]; });
print_r($filtered);

输出:

Array (
    [8709] => Array (
        [ref_id] => 116234
    )
    [8710] => Array (
        [ref_id] => 116234
    )
)

3v4l.org 上的演示


推荐阅读