[英]how to get the keys of similar values in an multidimensional array using php
我正在使用PHP中的多維數組。 我想檢測相似值的存在,然后計算相似值的數量並輸出結果。 例如,給定以下數組:
$products =
Array
(
[0] => Array
(
[price] => 100
[product] => cloths
[qty] => 3
)
[1] => Array
(
[price] => 101
[product] => cloths
[qty] => 10
)
[2] => Array
(
[price] => 102
[product] => cloths
[qty] => 16
)
[3] => Array
(
[price] => 103
[product] => cloths
[qty] => 1
)
[4] => Array
(
[price] => 108
[product] => cloths
[qty] => 6
)
[5] => Array
(
[price] => 107
[product] => cloths
[qty] => 4
)
[6] => Array
(
[price] => 109
[product] => cloths
[qty] => 5
)
[7] => Array
(
[price] => 105
[product] => cloths
[qty] => 2
)
[8] => Array
(
[price] => 104
[product] => cloths
[qty] => 5
)
[9] => Array
(
[price] => 106
[product] => cloths
[qty] => 2
)
[10] => Array
(
[price] => 111
[product] => cloths
[qty] => 1
)
)
如何解決這個問題?
foreach ($products as $key => $product) {
$price = $product['price'];
//now using this price how can i get all keys which are equal to this price
}
編輯我已經嘗試過但沒有用
echo $key = array_search(100, array_column($products, 'price'));
請嘗試以下方法:
$keys = array_keys(array_filter($product, function($val) {return $val['price'] == 100; })
我將創建一個包含價格作為鍵和產品鍵作為值的數組:
$prices = array();
foreach ($products as $key => $product) {
$prices[$product['price']][] = $key;
}
現在, $prices[105]
包含價格= 105的所有產品密鑰的數組(在特定示例中,只有一個: 7
):
var_dump($prices[105]);
# array(1) {
# [0]=>
# int(7)
# }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.