![](/img/trans.png)
[英]PHP: How can I easily combine or merge simpleXML elements using a node value?
[英]How can I map an integer value to a string more easily in PHP?
如何重構以下代碼以使其更簡潔、更易於維護?
if ($row['vocation'] == 1) $vocation = "sorcerer";
if ($row['vocation'] == 2) $vocation = "druid";
if ($row['vocation'] == 3) $vocation = "paladin";
if ($row['vocation'] == 4) $vocation = "knight";
if ($row['vocation'] == 5) $vocation = "master sorcerer";
if ($row['vocation'] == 6) $vocation = "elder druid";
if ($row['vocation'] == 7) $vocation = "royal paladin";
if ($row['vocation'] == 8) $vocation = "elite knight";
else $vocation = "none";
我建議使用數組,如下所示:
static $vocations = array(
1 => 'sorceror',
2 => 'druid',
3 => 'paladin',
4 => 'knight',
5 => 'master sorceror',
6 => 'elder druid',
7 => 'royal paladin',
8 => 'elite knight',
);
$vocation =
isset($vocations[$row['vocation']]) ? $vocations[$row['vocation']] : 'none';
這是使用開關執行此操作的示例:
switch ($row['vocation']) {
case 1:
$vocation = "sorcerer";
break;
case 2:
$vocation = etc..
default:
$vocation = "none";
}
這對於 C、Java 和 C# 等許多語言以及許多其他語言來說都是常見的事情。
這是另一個建議:
<?php
class Action
{
const TYPE__ADD = 0;
const TYPE__VIEW = 1;
const TYPE__EDIT = 2;
const TYPE__PATCH = 3;
const TYPE__DELETE = 4;
const TYPE__MAP = [
self::TYPE__ADD => 'add',
self::TYPE__VIEW => 'access',
self::TYPE__EDIT => 'edit',
self::TYPE__PATCH => 'patch',
self::TYPE__DELETE => 'delete'
];
protected $type;
public function setType(int $type)
{
if (!isset(self::TYPE__MAP[$this->type])) throw new \Exception(sprintf('Invalid type. Possible options are: %s.', implode(',', self::TYPE__MAP)));
$this->type = $type;
}
public function getType(): int
{
return $this->type;
}
public function getTypeStr(): string
{
return self::TYPE__MAP[$this->type];
}
}
// Test
$action = new Action();
$action->setType(Action::TYPE__PATCH);
echo 'Action type is: '.$action->getTypeStr().', and its representative int value is: '.$action->getType();
下一塊可能會好一點。 8 個元素是可以的,但是如果列表包含 1000 個呢?
$list = array("sorcerer", "druid", ...);
$vocation = "none";
if($row['vocation'] <= count($list)){
$vocation = $list[$row['vocation'] - 1];
}
我會使用數組的建議,我會使用常量來表示這樣的整數值:
define('VOCATION_SORCEROR', 1);
define('VOCATION_DRUID', 2);
define('VOCATION_PALADIN', 3);
$vocations = array(
VOCATION_SORCEROR => 'sorceror',
VOCATION_DRUID => 'druid',
VOCATION_PALADIN => 'paladin'
);
正確地開始你的項目,現在使用 const 來表示這些數字常量,並為自己省去一些麻煩。 (除了像其他人建議的那樣使用 switch/case 之外)
https://codingonly4u.blogspot.com/2019/12/adding-google-map-with-marker-to-your.html我從這里得到了解決方案。 將 map 與引腳集成
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.