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条)

报告相同问题?

悬赏问题

  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?