php - 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?
解决方案
您的代码不起作用,因为$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
)
)
推荐阅读
- while-loop - 带有条件和空值的 Talend tLoop 问题
- javascript - JavaScript 和 HTML 更改未通过 Django 服务器出现
- python - 计算数据框列中最常见的值组合
- arrays - 如何合并数组和数组scala spark
- swift - 声明一个符合协议的未知类型的变量?
- excel - Excel 组合框下拉(表单控件)在受保护时不起作用
- java - JTable 单元格渲染器使用其他单元格背景设置背景
- python - 使用python时无法从json文件加载图像进行预测
- javascript - 我如何将一个对象变成一个对象数组?
- azure-functions - Azure 服务总线函数 Message.SessionId 与 MessageSession.SessionId 不同