我有一个如下所示的数组,我想要最小值及其搜索税类ID的索引
Array
(
[tax_class_id] => Array
(
[0] => 12
[1] => 13
[2] => 13
)
[price] => Array
(
[0] => 6233
[1] => 3195
[2] => 19192
)
)
我在tax_class_id中搜索最低价格和相应的密钥。在这个Senario中,我要求最低价格,即3195和tax_id - 13,即关键[1]
我的代码是
$prod_total = array();
for($i = 1;$i <= $chunk;$i++){
if($i == 1) {
$min_product_amt = min($product_amt['price']);
$index = array_search($min_product_amt, $product_amt);
$product_total = $min_product_amt;
//ceil Round numbers up to the nearest integer
$prod_total['price'] = ceil($product_total * $discount/100);
$prod_total['tax_id'] = $product_amt['tax_class_id'];
//Remove the first element from an array
array_shift($product_amt['price']);
array_shift($product_amt['tax_class_id']);
} else {
$second_min_product_amt = min($product_amt['price']);
$index = array_search($min_product_amt, $product_amt);
$product_total = $second_min_product_amt;
$prod_total['price'] = ceil($product_total * $discount/100);
$prod_total['tax_id'] = $product_amt['tax_class_id'];
array_shift($product_amt['price']);
array_shift($product_amt['tax_class_id']);
}
}
print_r($prod_total);
die;
答案 0 :(得分:1)
$array=Array
(
'tax_class_id' => Array
(
0 => 12,
1 => 13,
2 => 13
),
'price' => Array
(
0 => 6233,
1 => 3195,
2 => 19192
)
);
$minValue= min($array['price']);
$minKey=array_keys($array['price'], $minValue);
$tax_id=$array['tax_class_id'][$minKey[0]];
echo $tax_id;
此代码适用于您的问题。首先,我得到嵌套数组price
的最小值,然后它与key
相关联。之后,我只访问嵌套数组tax_class_id
并获取我需要访问每个数组的字段的值。
答案 1 :(得分:1)
$data = [
"tax_class_id" => [
12,
13,
13
],
"price" => [
6233,
3195,
19192
]
];
$lowestFound;
foreach($data["price"] as $i => $price){
if(!$lowestFound || $lowestFound[1] > $price)
$lowestFound = [$i,$price];
}
echo $data["tax_class_id"][$lowestFound[0]];
此代码在一个周期内获得最低价格密钥的tax_class_id。
答案 2 :(得分:1)
我认为array_column为您提供了一个很好的输出。
$array=Array
(
'tax_class_id' => Array(
0 => 12,
1 => 13,
2 => 13
),
'price' => Array(
0 => 6233,
1 => 3195,
2 => 19192
)
);
// Find minimum value
$min= min($array['price']);
// Find key of min value
$Key=array_search($min, $array['price']);
// Extract all values with key[min value]
$new = array_column($array, $Key);
Var_dump($new);
$ new的输出现在是
array(2) {
[0]=> int(13)
[1]=> int(3195)
}
基本上是您要寻找的两个值 https://3v4l.org/NsdiS