我有这个数组:
$transfers =
Array
(
[0] => Array
(
[agency_to_id] => 8
[agency_name] => 3.1 SUCURSAL BRASILIA
[product_id] => 415
[product_code] => 111021
[product_name] => PAN FELIPE POR KILO
[ptype_id] => 54
[ptype_name] => 1.1.01.1 PANADERIA X KILO
[catalog_id] => 1
[subject_id] => 3
[label_id] => 300000002
[total_quantity] => 12
)
[1] => Array
(
[agency_to_id] => 9
[agency_name] => 4.1 SUCURSAL CENTRO
[product_id] => 415
[product_code] => 111021
[product_name] => PAN FELIPE POR KILO
[ptype_id] => 54
[ptype_name] => 1.1.01.1 PANADERIA X KILO
[catalog_id] => 1
[subject_id] => 3
[label_id] => 300000002
[total_quantity] => 8
)
[2] => Array
(
[agency_to_id] => 8
[agency_name] => 3.1 SUCURSAL BRASILIA
[product_id] => 416
[product_code] => 111024
[product_name] => GALLETA POR KILO
[ptype_id] => 54
[ptype_name] => 1.1.01.1 PANADERIA X KILO
[catalog_id] => 1
[subject_id] => 3
[label_id] => 300000002
[total_quantity] => 1.6
)
[3] => Array
(
[agency_to_id] => 8
[agency_name] => 3.1 SUCURSAL BRASILIA
[product_id] => 418
[product_code] => 111028
[product_name] => PAN INTEGRAL POR KILO
[ptype_id] => 54
[ptype_name] => 1.1.01.1 PANADERIA X KILO
[catalog_id] => 1
[subject_id] => 3
[label_id] => 300000002
[total_quantity] => 200
)
)
Run Code Online (Sandbox Code Playgroud)
我希望得到这个数组中与特定子数组值匹配的所有键,例如我想得到匹配的键,[product_id] => 415我应该得到键0和1
我尝试过array_keys,但它不起作用.
编辑:
foreach ($transfers $key => $transfer) {
$found_keys = array_keys($transfers, $transfer['product_id']);
}
Run Code Online (Sandbox Code Playgroud)
所以,你的答案,是一个空数组
foreach ($transfers $key => $transfer) {
$filteredKeys = array_keys(array_filter($transfers,
function($item) {
return $item['product_id'] === $transfer['product_id'];
}));
}
Run Code Online (Sandbox Code Playgroud)
你能帮我吗.谢谢
编辑后:
$found_keys = array();
foreach ($transfers as $key => $transfer) {
if ($transfer['product_id'] === 415) $found_keys[] = $key;
}
Run Code Online (Sandbox Code Playgroud)
在最初陈述的问题的解决方案下面:
使用array_filter如下:
$filtered = array_filter($transfers,
function($item) {
return $item['product_id'] === 415;
});
Run Code Online (Sandbox Code Playgroud)
获得所有匹配的元素,完成.
要仅获取密钥,请将结果传递给array_keys:
$filteredKeys = array_keys(array_filter($transfers,
function($item) {
return $item['product_id'] === 415;
}));
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为array_filter在结果数组中保留了源数组的键.