我试图在 milti 数组的数组中查找一个值,找到它后,我想返回一个不同的键,不知道如何进一步解释。
我有一个数组:
tempArray( [0] => Array
(
[id] => 18460
[field_id] => 14
[parent_id] => 165
[custom_tab_field_id] => 17775
[status] => 0
[field_type] => 0
)
[1] => Array
(
[id] => 18461
[field_id] => 2
[parent_id] => 165
[custom_tab_field_id] => 17776
[status] => 0
[field_type] => 2
)
[2] => Array
(
[id] => 18462
[field_id] => 12
[parent_id] => 165
[custom_tab_field_id] => 17777
[status] => 2
[field_type] => 2
))
我正在尝试通过 [custom_tab_field_id] 查找数组,并返回当前的数组 [status]。
我创建了一个应该执行此操作的函数,但它总是返回 0。
功能:
function searchForStatus($id, $array){
$returnedStatus = "0";
foreach ($array as $key => $val){
if ($val['custom_tab_field_id'] == $id){
return $returnedStatus = $array[$key]['status'];
}
}
return $returnedStatus;
}
然后只需通过传递值来调用该函数
$returnedStatus = searchForStatus($field['custom_tab_field_id'], $tempArr);
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
可以使用
array-filter函数来解决。即$a1 = [ ['id' => 1, 'status', 'active'], ['id' => 2, 'status', 'in-active'] ]; $search = 2; print_r(array_filter($a1, function ($object) use ($search) { return $object['id'] == $search; }));它将从与
搜索id 匹配的数组中返回整个数组。你也可以为此编写一个函数
function search($data, $searchValue, $searchField, $returnField) { $filter = array_filter($data, function ($object) use ($searchValue, $searchField) { return $object[$searchField] == $searchValue; }); return count($filter) > 0 ? $filter[0][$returnField] : null; }使用 array_column 函数,这可以轻松实现已解决并且非常通用。
该解决方案不包含错误处理,仅展示原理。 $arrKeyValue 是一个数组,如何:
尝试自行https://3v4l.org/SnVM4