我有这个数组:
$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
)
)
我想得到这个数组中与特定子数组值匹配的所有键,例如我想得到与[product_id] => 415
匹配的键,我应该得到键0和1
我尝试过使用array_keys,但它不起作用。
编辑:
foreach ($transfers $key => $transfer) {
$found_keys = array_keys($transfers, $transfer['product_id']);
}
所以,你的答案,是一个空数组
foreach ($transfers $key => $transfer) {
$filteredKeys = array_keys(array_filter($transfers,
function($item) {
return $item['product_id'] === $transfer['product_id'];
}));
}
你能帮帮我吗?谢谢
答案 0 :(得分:6)
编辑后:
$found_keys = array();
foreach ($transfers as $key => $transfer) {
if ($transfer['product_id'] === 415) $found_keys[] = $key;
}
在最初陈述的问题的解决方案之下:
像这样使用array_filter
:
$filtered = array_filter($transfers,
function($item) {
return $item['product_id'] === 415;
});
获取所有匹配元素,完成。
要仅获取密钥,请将结果传递给array_keys
:
$filteredKeys = array_keys(array_filter($transfers,
function($item) {
return $item['product_id'] === 415;
}));
这很有效,因为array_filter
会在结果数组中保留源数组的键。
答案 1 :(得分:3)
听起来像是foreach
:
$found_keys = array();
foreach($transfers as $transfer){
if($transfer['product_id'] == 415){
array_push($found_keys, $transfer);
}
}
答案 2 :(得分:1)
将array_column
和array_keys
与搜索参数一起使用。以下是它的工作原理示例:
$products = array(
0 => array('product_id'=>3),
1 => array('product_id'=>4),
2=> array('product_id'=>3)
);
$keys = array_keys(array_column($products, 'product_id'), 3);
// outputs the key of the element that has `product_id` = 3
var_dump($keys);
答案 3 :(得分:0)
循环,循环和循环。这是关键。 (得到它?关键?对不起)
总之:
</pre></code>