【问题标题】:Is there a more efficient way to write this bit of php code?有没有更有效的方法来编写这段 php 代码?
【发布时间】:2013-11-12 10:05:00
【问题描述】:

有没有更高效/优雅的方式来编写这段代码:

$arr1 = array(
        "weedoit3",
        "alambic3",
        "darwinefficiencyscared",
        "darwinmoneyscared",
        "darwin5scared");

$arr2 = array(
        "darwingouroo",
        "weedoit4",
        "darwin5",
        "darwinefficiency",
        "darwinmoney",
        "pj_half",
        "pj_pole");

$imgArray = array(
        '<img src="images/mail26bg.jpg" width="1440" height="810" class="thiefBg" />',
        '<img src="images/mail25bg.jpg" width="819" height="1024" class="thiefBg" />',
        '<img src="images/mai01.jpg" width="1440" height="960" class="thiefBg" />',
        '<img src="images/mai02.jpg" width="1440" height="960" class="thiefBg" />',
        '<img src="images/mai03.jpg" width="1440" height="1081" class="thiefBg" />');

if (in_array($_GET['ref'], $arr1)) {
    echo $imgArray[0];
}
else if (in_array($_GET['ref'], $arr2)) {
    echo $imgArray[1];
}
else if ($_GET['ref'] == "darwin4" || $_GET['ref'] == "darwinenquete") {
    echo $imgArray[2];
}
else if ($_GET['ref'] == "darwinscared") {
    echo $imgArray[3];
}
else if ($_GET['ref'] == "mai03") {
    echo $imgArray[4];
}

【问题讨论】:

    标签: php arrays performance


    【解决方案1】:

    将 ref 映射到索引。

    $refMap = Array('weedoit3' => 0, 'alambic' => 0, ... 'mai03' => 4);
    
    echo $imgArray[$refMap[$_GET['ref']]];
    

    【讨论】:

    • 谢谢,这正是我所需要的。
    【解决方案2】:

    总是比in_array 快是isset。

    所以你可以像这样定义你的查找数组:

    <?php
    // Trick here: Use your values as keys and assign them an empty string:
    $arr1 = array('weedoit3' => '',
                  'alambic3' => '',
                  // ...
                 );
    
    // Then the check:
    if(true === isset($arr1[$_GET['ref'])
    {
        // do whatever
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      • 2022-12-08
      相关资源
      最近更新 更多