我正在导入产品列表,每个项目都有一个部门编号。每个数字都与一个部门相关,即
共有43个部门。我会做一个很长的if语句,如:
`<?php
if ($var = 1)
echo "Handguns";
else
if ($var = 2)
echo "Used Handguns";
等..... ?&gt;`
编辑:我能够得到这样的if语句:
function test($cat) {
if ($cat = 33)
echo "Clothing";
}
但是使用这样的任何数组:
`$ departments = [ 33 =&gt;服装, ];
function getDepartment($ id,$ departments){ echo $ departments [$ id]; }`
我一直无法上班。我正在使用wordpress并将其放在functions.php中并从插件中调用该函数。
我应该坚持使用一个大的if语句吗?
第二次编辑:通过在函数中包含数组来实现它:
function getDepartment($id, $departments) {
$departments = [
"1" => "Handguns",
"2" => "Used Handguns",
"3" => "Used Long Guns",
"4" => "Tasers",
"5" => "Sporting Long Guns",
"6" => "SOTS ",
...
"41" => "Upper Receivers/Conv Kits",
"42" => "SBR Barrels and Uppers ",
"43" => "Upper/Conv Kits High Cap"
];
if (isset($departments[$id])) {
return $departments[$id];
}
return 'Uncategorized';
}
并且在wpallimport内部,类别调用看起来像这样:[getDepartment({column_4 [1]})]
答案 0 :(得分:2)
使用ID作为数组键创建部门数组。然后,您可以使用基本数组变量语法访问它们:
$departments = array(
1 => Handguns,
2 => Used Handguns,
3 => Used Long Guns,
4 => Tasers,
5 => Sporting Long Guns
);
$var = 2;
echo $departments[$var]; // prints "Used Handguns"
您可以随意构建此数组。它可以在配置文件中进行硬编码,也可以通过SQL查询创建。
在尝试访问之前,确保密钥存在于数组中,否则会收到未定义的索引错误消息。将这个放在一个函数中可能是明智之举,这样你就可以抽象出这个代码,并在每次尝试访问这个数组时减少重复的代码。
function getDepartment($id, $departments) {
if (isset($departments[$id])) {
return $departments[$id];
}
return 'Invalid Department'; // or whatever you want if the value doesn't exist
}
echo getDepartment(2); // prints "Used Handguns"