一个带有某些索引值的php数组

时间:2019-05-29 22:21:35

标签: php arrays

我想用这样的东西创建数组或函数n php:
在1-20之间的索引将返回“类型1”
对于介于20-25之间的索引,返回“类型2”
对于介于25-35之间的索引,返回“类型1”
在35-40之间的索引返回“类型3”
索引介于40-60 retusn“类型2”之间。

我该怎么做?
例如,id 1,id 22,id 50可以是类型1,id 2,id 23,id 51也可以是类型2。

我已经尝试过了:

function getSkinType($id) {
    $skins = array(
        0,13,40,46,47,59,60,72,73,76,82,83,84,85,90,91,93,98,102,103,104,105,106,107,108,109,110,111,112, 113,114,115,116,120,121,123,124,125,126,127,128,141,147,150,163,164,165,166,169,170,173,174,175,177,181,185,186,187,189,191,193,194,192,195,203,204,216,219,221,223,228,233,240,258,259,263,269,270,271,272,290,292,293,294,295,296,297,298,299,3 => "premium",
        2,7,9,11,14,15,16,17,19,20,21,22,18,23,24,25,28,29,30,32,33,34,35,36,41,43,44,45,48,51,52,57,58,63,64,66,67,69,88,92,95,96,97,100,101,122,131,133,138,139,140,142,143,148,154,155,156,167,171,172, 176,179,180,182,183, 184,188,190,201,202,206,214,215,222,224,225,226,227,234,238,247,248,249,250,251,252 => "normal",
        1,12,27,31,37,50,56,78,79,129,134,135,136,137,152,153,157,158,159,160,161,162,196,200,212 => "default"
    );
    return $skins[$id];
}

2 个答案:

答案 0 :(得分:1)

一种可能的方法是简单地使用$kins数组中的索引来表示类别。这可以传递给函数本身。例如,如果要检索82外观(在第一类别的索引10处),则可以使用 the following

<?php

function getSkinType($category, $id) {
$skins = array(
    [0,13,40,46,47,59,60,72,73,76,82,83,84,85,90,91,93,98,102,103,104,105,106,107,108,109,110,111,112, 113,114,115,116,120,121,123,124,125,126,127,128,141,147,150,163,164,165,166,169,170,173,174,175,177,181,185,186,187,189,191,193,194,192,195,203,204,216,219,221,223,228,233,240,258,259,263,269,270,271,272,290,292,293,294,295,296,297,298,299,3],
    [2,7,9,11,14,15,16,17,19,20,21,22,18,23,24,25,28,29,30,32,33,34,35,36,41,43,44,45,48,51,52,57,58,63,64,66,67,69,88,92,95,96,97,100,101,122,131,133,138,139,140,142,143,148,154,155,156,167,171,172,176,179,180,182,183, 184,188,190,201,202,206,214,215,222,224,225,226,227,234,238,247,248,249,250,251,252],
    [1,12,27,31,37,50,56,78,79,129,134,135,136,137,152,153,157,158,159,160,161,162,196,200,212]
);
    return $skins[$category][$id];
}

echo getSkinType(0, 10); // 82

在上面,类别0对应于溢价,1对应于normal,而2对应于default。如果需要,可以为此设置变量,而改用这些变量。

另一种方法是使用关联数组而不是类别索引,但这实际上完成了相同的事情。

答案 1 :(得分:0)

尝试一下

function getSkinType($id) {
     $grouping = [
         'type 1' => [1, 13, 20, 25, 35], // [ ids ]
         'type 2' => [20, 25],
         'type 3' => [35, 40],
     ];

     foreach($grouping as $type => $range) {
         if (in_array($id, $range))  {
              return $type;
         }
     }

     return 'Type not found'; // default text here
}


echo getSkinType(13); // "type 1"