【发布时间】:2018-03-15 22:52:33
【问题描述】:
我想知道是否可以稍微清理一下此代码...我有一系列汽车类别,每个键都是一个车辆代码。我将几个车辆代码映射到特定类别(例如小型、中型、大型)。我之前问过一个类似的问题,但我不确定它是否清楚,所以我简化了我的问题。 我想保持这种类似的格式,但想知道是否可以做这样的事情(这样我就不必多次写“Small”了):
$categories = [
'L...' => 'Luxury',
'W...' => 'Luxury',
'X...' => 'Specialty',
'CB..', 'CC..', 'CD..' => 'Small'
// Is something like this possible to do within the $categories array ?
];
当前代码:
$categories = [
'L...' => 'Luxury',
'W...' => 'Luxury',
'X...' => 'Specialty',
'CB..' => 'Small',
'CC..' => 'Small',
'CD..' => 'Small',
'DB..' => 'Small',
'DC..' => 'Small',
'DD..' => 'Small',
'EB..' => 'Small',
'EC..' => 'Small',
'ED..' => 'Small',
'HB..' => 'Small',
'HC..' => 'Small',
'HD..' => 'Small',
'MB..' => 'Small',
'MC..' => 'Small',
'MD..' => 'Small',
'NB..' => 'Small',
'NC..' => 'Small',
'ND..' => 'Small',
'IB..' => 'Medium',
'IC..' => 'Medium',
'ID..' => 'Medium',
'JB..' => 'Medium',
'JC..' => 'Medium',
'JD..' => 'Medium',
'RB..' => 'Medium',
'RC..' => 'Medium',
'RD..' => 'Medium',
'SB..' => 'Medium',
'SC..' => 'Medium',
'SD..' => 'Medium',
'FB..' => 'Large',
'FC..' => 'Large',
'FD..' => 'Large',
'GB..' => 'Large',
'GC..' => 'Large',
'GD..' => 'Large',
'PB..' => 'Large',
'PC..' => 'Large',
'PD..' => 'Large',
'UB..' => 'Large',
'UC..' => 'Large',
'UD..' => 'Large',
'.E..' => 'Sports', // Coupe
'.F..' => 'SUV',
'.G..' => 'SUV', // Crossover
'.H..' => 'RV', // Motor Home
'.J..' => 'Off-Road Vehicle',
'.K..' => 'Commercial',
'.L..' => 'Luxury', // Limousine
'.M..' => 'Van', // Monospace
'.N..' => 'Convertible', // Roadster
'.P..' => 'Pickup Truck',
'.Q..' => 'Pickup Truck',
'.R..' => 'RV',
'.S..' => 'Sports',
'.T..' => 'Convertible',
'.V..' => 'Van',
'.W..' => 'Wagon',
'.X..' => 'Specialty',
'.Z..' => 'Specialty',
'...C' => 'Electric',
'...E' => 'Electric',
'...H' => 'Hybrid',
'...I' => 'Hybrid'
];
【问题讨论】:
-
为什么不使用多维数组,反过来呢?例如
$categories = ['Luxury' => ['L','W'], 'Specialty' => ['X'] ... and so on ... ]; -
为什么要在代码中存储这些数据?
-
@CD001 啊,这很好 - 如果我这样做,我将如何循环每个值?
-
完全取决于您要执行的操作,您可以使用recursive array search 来查找您所追求的项目 - 尽管您最初最好以不同的方式构造数据,在数据库或者甚至是 XML 文件,那么您就有了更多现成的功能。
标签: php arrays key refactoring code-cleanup