我有一個陣列裏面有大約3500個數組項,格式如下。我有兩個動態變量發生了變化,我需要根據已知的price_slot和country來搜索數組以找出行price_value。快速搜索PHP數組
我目前已經得到了下面,但這是花了太長時間。無論如何,我可以加快訪問速度嗎?
PHP函數
$country = US;
$priceSlot = 3;
$priceValue = getPriceValue($priceSlot, $country);
function getPriceValue($priceSlot, $country) {
// Search in array for price
foreach ($array as $arrayItem) {
if ($arrayItem['price_slot'] == $priceSlot && $arrayItem['country'] == $country) {
return $arrayItem['price_value'];
}
}
return null;
}
陣列的片段
Array
(
[0] => Array
(
[price_slot] => 1
[base_price] => Get in Touch
[country] => US
[price_multiplier] =>
[price_value] => Get in Touch
)
[1] => Array
(
[price_slot] => 2
[base_price] => 9000
[country] => US
[price_multiplier] => 1.3
[price_value] => 11700
)
[2] => Array
(
[price_slot] => 3
[base_price] => 12000
[country] => US
[price_multiplier] => 1.3
[price_value] => 15600
)
[3] => Array
(
[price_slot] => 4
[base_price] => 15000
[country] => US
[price_multiplier] => 1.3
[price_value] => 19500
)
[4] => Array
(
[price_slot] => 5
[base_price] => 4000
[country] => US
[price_multiplier] => 1.3
[price_value] => 5200
)
[5] => Array
(
[price_slot] => 6
[base_price] => 1600
[country] => US
[price_multiplier] => 1.3
[price_value] => 2080
)
有沒有更快的方法來解決這個問題?
謝謝!
你如何填充你的數組?如果您總是檢查'price_slot'和'country',那麼在構建數組時可能會將該組合用作數組索引,而不是使用數字索引。然後你可以簡單地使用'isset()'來檢查它是否存在,並返回它的'price_value'。 – rickdenhaan
看起來應該是這樣的DB – nogad
我通過csv @rickdenhaan填充數組,所以不能動態檢查那個不幸的! – DIM3NSION