【问题标题】:Replace column values in result set using a lookup/dictionary array使用查找/字典数组替换结果集中的列值
【发布时间】:2016-09-13 15:11:14
【问题描述】:

您可以在下面找到整个代码。

我有 2 个数组。第一个数组如下所示:

// Replace ID_CHAT_ with readable value
$replacements = array(
    'ID_CHAT_ATTACK/DEFEND' => 'Attack/Defend!',
    'ID_CHAT_REQUEST_MEDIC' => 'Request Medic!',
    'ID_CHAT_REQUEST_AMMO' => 'Request Ammo!',
    'ID_CHAT_REQUEST_RIDE' => 'Request Ride!',
    'ID_CHAT_NEGATIVE' => 'Negative!',
    'ID_CHAT_SORRY' => 'Sorry!',
    'ID_CHAT_GOGOGO' => 'Go Go Go!',
    'ID_CHAT_AFFIRMATIVE' => 'Affirmative!',
    'ID_CHAT_REQUEST_ORDER' => 'Request Order!',
    'ID_CHAT_THANKS' => 'Thanks!',
);

第二个数组是这样的:(来自 mysqli 结果集)

[31] => Array
    (
        [ID] => 2179
        [logDate] => 2016-05-12 22:10:38
        [ServerID] => 2
        [logSubset] => Team
        [logSoldierName] => OPTIMUS-GOLD
        [logMessage] => ID_CHAT_REQUEST_AMMO
        [logPlayerID] => 1071
    )

[32] => Array
    (
        [ID] => 2178
        [logDate] => 2016-05-12 22:10:34
        [ServerID] => 2
        [logSubset] => Team
        [logSoldierName] => CaptaineGamingFR
        [logMessage] => ID_CHAT_REQUEST_RIDE
        [logPlayerID] => 1531
    )

[33] => Array
    (
        [ID] => 2177
        [logDate] => 2016-05-12 22:10:27
        [ServerID] => 2
        [logSubset] => Team
        [logSoldierName] => CaptaineGamingFR
        [logMessage] => ID_CHAT_GOGOGO
        [logPlayerID] => 1531
    )

[34] => Array
    (
        [ID] => 2176
        [logDate] => 2016-05-12 22:10:11
        [ServerID] => 2
        [logSubset] => Global
        [logSoldierName] => CaptaineGamingFR
        [logMessage] => cool des francais
        [logPlayerID] => 1531
    )

[35] => Array
    (
        [ID] => 2175
        [logDate] => 2016-05-12 22:10:08
        [ServerID] => 2
        [logSubset] => Global
        [logSoldierName] => Minotaures
        [logMessage] => et sa s affiche sur tt les serveur
        [logPlayerID] => 1337
    )

我想将第二个数组中的 logMessage 值替换为对应的$replacements 值。

它应该是什么样子:

[logMessage] => **ID_CHAT_REQUEST_AMMO**

必须

[logMessage] => Request Ammo!

当前代码:

public function serverChatlog( $serverID = null ) {
        
    // Replace ID_CHAT_ with readable value
    $replacements = array(
        'ID_CHAT_ATTACK/DEFEND' => 'Attack/Defend!',
        'ID_CHAT_REQUEST_MEDIC' => 'Request Medic!',
        'ID_CHAT_REQUEST_AMMO' => 'Request Ammo!',
        'ID_CHAT_REQUEST_RIDE' => 'Request Ride!',
        'ID_CHAT_NEGATIVE' => 'Negative!',
        'ID_CHAT_SORRY' => 'Sorry!',
        'ID_CHAT_GOGOGO' => 'Go Go Go!',
        'ID_CHAT_AFFIRMATIVE' => 'Affirmative!',
        'ID_CHAT_REQUEST_ORDER' => 'Request Order!',
        'ID_CHAT_THANKS' => 'Thanks!',
    );
        
    // Create an array.
    $output = array();
        
    // Query the database
    $query  = $this->connectDB()->query( 'SELECT * FROM `tbl_chatlog` ORDER BY `ID` DESC' );
    $result = $query->num_rows;
    $array  = $query->fetch_all(MYSQLI_ASSOC);
        
    // Return the results in JSON format
    if( $result > 0 ) {
        $output = json_encode( $array, JSON_PRETTY_PRINT );
        return json_decode( $output, true );
    } else {
        return false;
    }
}

【问题讨论】:

  • 您已经尝试过什么了吗?如果您需要线索,请查看array_search 方法
  • 是的,我尝试了很多东西。还有 Allen Butler 的遮阳篷。但是,它只替换 1 个值而不是所有值。

标签: php mysql arrays mysqli replace


【解决方案1】:

如果您在函数中硬编码$replacements,那么您不妨直接将其构建到您的sql 中。使用CASE 语句。

让fetch_all() 返回一个 json 编码的数组(即使它是空的)。尽可能在返回值中保持一致的数据类型是个好主意。

public function serverChatlog(): string
{
    $sql = "SELECT ID,
                   logDate,
                   ServerID,
                   logSubset,
                   logSoldierName,
                   CASE logMessage
                       WHEN 'ID_CHAT_ATTACK/DEFEND' THEN 'Attack/Defend!'
                       WHEN 'ID_CHAT_REQUEST_MEDIC' THEN 'Request Medic!'
                       WHEN 'ID_CHAT_REQUEST_AMMO'  THEN 'Request Ammo!'
                       WHEN 'ID_CHAT_REQUEST_RIDE'  THEN 'Request Ride!'
                       WHEN 'ID_CHAT_NEGATIVE'      THEN 'Negative!'
                       WHEN 'ID_CHAT_SORRY'         THEN 'Sorry!'
                       WHEN 'ID_CHAT_GOGOGO'        THEN 'Go Go Go!'
                       WHEN 'ID_CHAT_AFFIRMATIVE'   THEN 'Affirmative!'
                       WHEN 'ID_CHAT_REQUEST_ORDER' THEN 'Request Order!'
                       WHEN 'ID_CHAT_THANKS'        THEN 'Thanks!'
                       ELSE logMessage
                   END logMessage,
                   logPlayerID
            FROM `tbl_chatlog`
            ORDER BY `ID` DESC";
    return json_encode($this->connectDB()->query($sql)->fetch_all(MYSQLI_ASSOC), true);
}

看看你的方法变得多么干净、专业、直接和可读。

【讨论】:

    【解决方案2】:

    我希望这会有所帮助。搜索数组 key ,如果 key 存在则直接替换。

    foreach ($secondArray as &$value) {
        $key = array_search ( trim($value['logMessage'], '*') , $value );
        if (!empty($key)) {
            $value['logMessage'] = $replacements[$key]
        }
    }
    

    【讨论】:

    • 当$key 被保证被声明时,isset($key) && !empty($key) 不仅是不必要的,isset($key) && !empty($key) 是一个反模式,不应该以任何理由存在于任何人的代码中。 stackoverflow.com/a/4559976/2943403
    • empty() 不知道零和假之间的区别。不需要检查变量是否被声明,所以empty() 是一个糟糕的选择。
    【解决方案3】:

    可能类似于以下内容。抓取$replacements的键值,如果找到$array中的键值,则将其替换为$replacement值。

    $array = [
            "ID" => "2179",
            "logDate" => "2016-05-12 22:10:38",
            "ServerID" => "2",
            "logSubset" => "Team",
            "logSoldierName" => "OPTIMUS-GOLD",
            "logMessage" => "ID_CHAT_REQUEST_AMMO",
            "logPlayerID" => "1071"
    
    ];
     $replacements = array(
        'ID_CHAT_ATTACK/DEFEND' => 'Attack/Defend!',
        'ID_CHAT_REQUEST_MEDIC' => 'Request Medic!',
        'ID_CHAT_REQUEST_AMMO' => 'Request Ammo!',
        'ID_CHAT_REQUEST_RIDE' => 'Request Ride!',
        'ID_CHAT_NEGATIVE' => 'Negative!',
        'ID_CHAT_SORRY' => 'Sorry!',
        'ID_CHAT_GOGOGO' => 'Go Go Go!',
        'ID_CHAT_AFFIRMATIVE' => 'Affirmative!',
        'ID_CHAT_REQUEST_ORDER' => 'Request Order!',
        'ID_CHAT_THANKS' => 'Thanks!',
    );
    $keys = array_keys($replacements);
    foreach($array as $k => $v) {
        if(in_array($v, $keys)) {
            $array[$k] = $replacements[$v];
        }
    }
    print_r($array);
    //PRINTS: Array ( [ID] => 2179 [logDate] => 2016-05-12 22:10:38 [ServerID] => 2 [logSubset] => Team [logSoldierName] => OPTIMUS-GOLD [logMessage] => Request Ammo! [logPlayerID] => 1071 ) 
    

    编辑

    所以让我将相同的逻辑应用到数组的其余部分。假设我们有以下数组(我从上面的问题中提取了这个):

    $array = [
    "31" => 
        [
            "ID" => "2179",
            "logDate" => "2016-05-12 22:10:38",
            "ServerID" => "2",
            "logSubset" => "Team",
            "logSoldierName" => "OPTIMUS-GOLD",
            "logMessage" => "ID_CHAT_REQUEST_AMMO",
            "logPlayerID" => "1071"
        ],
    
    "32" => 
        [
            "ID" => "2178",
            "logDate" => "2016-05-12 22:10:34",
            "ServerID" => "2",
            "logSubset" => "Team",
            "logSoldierName" => "CaptaineGamingFR",
            "logMessage" => "ID_CHAT_REQUEST_RIDE",
            "logPlayerID" => "1531"
        ],
    
    "33" =>
        [
            "ID" => "2177",
            "logDate" => "2016-05-12 22:10:27",
            "ServerID" => "2",
            "logSubset" => "Team",
            "logSoldierName" => "CaptaineGamingFR",
            "logMessage" => "ID_CHAT_GOGOGO",
            "logPlayerID"  => "1531"
        ],
    "34" => [
            "ID" => "2179",
            "logDate" => "2016-05-12 22:10:38",
            "ServerID" => "2",
            "logSubset" => "Team",
            "logSoldierName" => "OPTIMUS-GOLD",
            "logMessage" => "ID_CHAT_REQUEST_AMMO",
            "logPlayerID" => "1071"
    
       ]
    ];
    

    现在我可以使用以下代码遍历这个数组:

    $keys = array_keys($replacements); // Grab The Array Keys
    foreach($array as $subarray => $a) { // For Each loop to pull out the subarrays
        foreach($a as $k => $v) { // another to loop through those subarrays
            if(in_array($v, $keys)) { // if the value is found as a key in the replacements array do the following
                $array[$subarray][$k] = $replacements[$v]; // replace the current subarray index value with the value in the $replacements array
            }
        }
    }
    

    这将输出以下内容:

    Array
    (
        [31] => Array
            (
                [ID] => 2179
                [logDate] => 2016-05-12 22:10:38
                [ServerID] => 2
                [logSubset] => Team
                [logSoldierName] => OPTIMUS-GOLD
                [logMessage] => Request Ammo!
                [logPlayerID] => 1071
            )
    
        [32] => Array
            (
                [ID] => 2178
                [logDate] => 2016-05-12 22:10:34
                [ServerID] => 2
                [logSubset] => Team
                [logSoldierName] => CaptaineGamingFR
                [logMessage] => Request Ride!
                [logPlayerID] => 1531
            )
    
        [33] => Array
            (
                [ID] => 2177
                [logDate] => 2016-05-12 22:10:27
                [ServerID] => 2
                [logSubset] => Team
                [logSoldierName] => CaptaineGamingFR
                [logMessage] => Go Go Go!
                [logPlayerID] => 1531
            )
    
        [34] => Array
            (
                [ID] => 2179
                [logDate] => 2016-05-12 22:10:38
                [ServerID] => 2
                [logSubset] => Team
                [logSoldierName] => OPTIMUS-GOLD
                [logMessage] => Request Ammo!
                [logPlayerID] => 1071
            )
    
    )
    

    【讨论】:

    • 是的,这确实有效,但是,它只适用于一个值。例如:只有攻击/防御!将被替换。其余的将保持不变。无论如何,谢谢你的遮阳篷。我希望你现在可以帮助我:)
    • 不应该这样。我确实注意到您使用**$command** 来描述应将命令替换为其各自的值,而我没有编写代码来解析它。但是上面的代码应该可以工作。现在您需要做的是遍历您的主数组,然后使用我提供的代码进行迭代。我将进行编辑,以便您可以看到它的实际效果。
    • 我很感激。给你的另一件事。它在一个类里面。我不在课堂上打印结果,而是在另一个 PHP 文件中的课堂外打印。如果你愿意,我可以把全班发给你
    • 哦,在这里你能看到我从你的 awnser 得到的当前结果。 site1.h2505194.stratoserver.net/5/test.php
    • 没错,你可以决定要打印在哪里,我只是把它放在那里让你看到输出
    【解决方案4】:

    也许这会有所帮助。它遍历日志数组,检查 logMessage 元素的值并替换它。

    <?php
    
        foreach($logs as $log){
            $replacementKey =   str_replace('*', '', $log['logMessage']);
            if(array_key_exists($replacementKey, $replacements)){
                $log['logMessage'] = $replacements[$replacementKey];
            }
        }
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-13
      • 2018-02-08
      • 2020-05-25
      • 2018-03-08
      • 2020-01-06
      • 2021-10-01
      • 1970-01-01
      • 2013-06-22
      相关资源
      最近更新 更多