我有一个数组:
$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'];
}));
}你能帮帮我吗。谢谢
发布于 2015-10-15 14:15:24
编辑后:
$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在结果数组中保留了源数组的键。
发布于 2015-10-15 14:17:26
听起来像是foreach的工作
$found_keys = array();
foreach($transfers as $transfer){
if($transfer['product_id'] == 415){
array_push($found_keys, $transfer);
}
}发布于 2015-10-15 14:18:03
使用带有搜索参数的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);https://stackoverflow.com/questions/33150799
复制相似问题