替换变量的值


Replace Value of Variable

我有以下代码片段:

public function getShippingData()
{
    return array(
        'shipping_method' => $this->order->getShippingService(),
        'shipping_price'  => $this->getBaseShippingPrice(),
        'carrier_title'   => Mage::helper('M2ePro')->__('Amazon Shipping')
    );
}

我想更改它以替换shipping_method的值。 即

if ($shipping_method == 'valuea') {
    $shipping_method = 'value1';
}
if ($shipping_method == 'something') {
    $shipping_method = 'somethingelse';
}

我有完整的场景列表,因此根据shipping_method的值,我希望它等于其他东西。 有没有比拥有 100 个 if 语句更好的方法来实现这一目标?

我会为此创建一个数组并根据键替换值。

$new_shipping_methods = array(
    'valueA' => 'value1',
    'valueB' => 'value2',
    // ...
);
$shipping_method = $new_shipping_methods[$shipping_method];

查看开关控制结构。正是您所需要的,取决于一个变量的不同选项,消除了很多 if。