dongyun8138 2014-06-13 19:51
浏览 22
已采纳

最好的PHP函数输出多个选项中的一个

I'm importing a product list, and each item has a department number. Each number correlates with a department, i.e.

  1. Handguns
  2. Used Handguns
  3. Used Long Guns
  4. Tasers
  5. Sporting Long Guns

There are 43 departments. Would I just do one long if statement like:

`<?php
if ($var = 1) 
echo "Handguns";
else
if ($var = 2) 
echo "Used Handguns";

etc..... ?>`

EDIT: I'm able to get an if statement like this to work:

function test($cat) { if ($cat = 33) echo "Clothing"; }

but using any array like this:

`$departments = [ 33 => Clothing, ];

function getDepartment($id, $departments) { echo $departments[$id]; }`

I've been unable to get that to work. I'm using wordpress and putting this in functions.php and calling the function from a plugin.

Should I just stick with a big if Statement?

2nd EDIT: Got it to work by including the array inside the function:

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'; 
}

and inside wpallimport, the category call looked liked this: [getDepartment({column_4[1]})]

  • 写回答

1条回答 默认 最新

  • dtvam48220 2014-06-13 19:53
    关注

    Create an array of the departments using their ID as their array key. Then you can access them using basic array variable syntax:

    $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"
    

    You can construct this array however you like. It can be hardcoded in a config file or more likely created from a SQL query.

    Just make sure that the key exists in your array before you try to access it or else you get an undefined index error message. You probably would be wise to place this in a function so you can abstract this code and reduce duplicated code on each attempt to access this array.

    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?