dt250827 2016-07-12 16:58
浏览 8
已采纳

PHP数组,然后检查是否在数据中

I'm checking every possible thing in the array to see if it contains something from the data specified.

Array:

$dogs = [
    "terrier" => "Terrier",
    "german_shepard" => "GS",
];

Code:

if ($stmt->execute()){
    while ($request = $stmt->fetch(PDO::FETCH_ASSOC)){
        foreach($dogs as $x => $x_value){
            if (strpos($request['Data'], $x) !== false) { // This bit!!
               $dog = $x_value;
            } else {
               $dog = 'Unknown dog';
            }
        }
    }
}

I then have a list, It can detect the first one in the list fine, but others it just calls 'Unknown dog' EG:

1 - Terrier

2 - Unknown Dog

3 - Unknown Dog

I want it to appear like:

1 - Terrier

2 - GS

3 - GS

I want the list to appear for each value found.

  • 写回答

2条回答 默认 最新

  • dongxiatuo9827 2016-07-12 17:11
    关注

    You are overwriting the $dog variable for each item it checks in $dogs, so if there is anything that doesn't match after the one that does match, it will set it back to 'Unknown dog'. You should set $dog to a default value before your loop, and only overwrite it if it is found.

    $dog = 'Unknown dog';
    foreach($dogs as $x => $x_value){
        if (strpos($request['Data'], $x) !== false) { // This bit!!
            $dog = $x_value;
        }
    }
    

    There may be more than one value in $dogs that matches a particular instance of $request['Data']. If you use this code, $dog will be set to the last value from from $dogs that matches $request['Data']. If you want it to be set to the first matching value, then add a break; after $dog = $x_value; If you want something other than first or last, it will need to be more complex than this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?