我有一大堆值,需要與其他一些值相對應。到目前為止,我已經按照以下方式設定了一個陣列:
$result = array(
1 => 'Red',
2 => 'Orange',
3 => 'Yellow',
4 => 'Green'
);
我還有一個變數$input提供了一個數值。
我需要想辦法說出類似的話:
<?php if $input = any of the values in the array, then display its corresponding colour.
我的陣列串列最終會包含數百個值,所以如果有更好的方法來實作這一點,我會全力以赴。它必須在 PHP 中。
怎樣才能做到最好?非常感謝您提前提供幫助!
uj5u.com熱心網友回復:
這可以使用以下isset函式輕松完成:
<?php
$result = array(
1 => 'Red',
2 => 'Orange',
3 => 'Yellow',
4 => 'Green'
);
$input = 3;
if (isset($result[$input]))
echo $result[$input] . PHP_EOL;
要在一個范圍內查找:
$result = [
'1-2' => 'Red',
'2-5' => 'Orange',
'6-9' => 'Yellow',
'10-20' => 'Green'
];
$input = 8;
foreach ($result as $range => $colour) {
$split = explode('-', $range);
if ($input >= $split[0] && $input <= $split[1]) {
echo $colour . PHP_EOL;
}
}
注意:如果您不小心讓范圍以某種方式重疊,則此代碼會爆炸。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/334112.html
上一篇:從表格資料中輸出一個字串
