我需要检查几个名字,具体取决于与它们相关的数字。现在,我可以通过以下方式完成此任务。
$detectInspector = array();
$detectInspector[558]="Name";
$detectInspector[559]="OtherName";
$detectInspector[560]="Someone";
echo $detectInspector[558];
问题是我有数以百计的这些我必须输入。有没有更简单的方法来做一些像
这样的事情476 through 490 = name
518 through 530 = name
558 through 569 = othername
598 though 609 = othername
650 through 655 = someoneelse
690 through 695 = someoneelse
解释代码的工作原理:
答案 0 :(得分:0)
您可以尝试这样的事情:
首先将名称存储在具有名称条目的多维数组中,以及具有名称范围的数组。显然,如果数字在每个范围的最小值和最大值之间,则将设置名称。
$ranges = [
[
'name' => 'Jhon',
'ranges' => [
[1,50],
[120,200],
[401,409]
]
],
[
'name' => 'Jack',
'ranges' => [
[20,25],
[210,230],
],
],
[
'name' => 'Bill',
'ranges' => [
[245,270],
[301,350],
],
],
[
'name' => 'Steve',
'ranges' => [
[271,275],
],
],
];
$names = [];
foreach ($ranges as $nameProps) {
foreach ($nameProps['ranges'] as $range) {
list($min, $max) = $range;
$names[] = [
'name' => $nameProps['name'],
'min' => $min,
'max' => $max,
];
}
}
然后,假设您从db获取$ nb变量:
$nb = 999;
$detectInspector = [];
for ($i = 1; $i <= $nb; $i++) {
$name = '';
foreach ($names as $k => $nameProps) {
if ($i >= $nameProps['min'] && $i <= $nameProps['max']) {
$name .= ($name ? ' | ' : '') . $nameProps['name'];
}
}
if ($name != '') {
$detectInspector[$i] = $name;
}
}
您现在可以使用$ detectInspector值
var_dump($detectInspector);