首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在php中使用strpos查找对象中的特定单词

在php中使用strpos查找对象中的特定单词
EN

Stack Overflow用户
提问于 2020-03-23 05:35:28
回答 2查看 192关注 0票数 0

我正在尝试设置一个测试题,它将在简短的答案中找到特定的单词。将把答案标记为正确的单词将作为值存储在对象中。我试图找出如何使用strpos()来完成此任务,但是我想出的每个替代方案都会给我一个空白屏幕。

PHP:

代码语言:javascript
复制
$myJSON = file_get_contents('quiz.json');
$json = json_decode($myJSON); 
foreach($json as $value) {
    foreach($value->answer as $index => $options) {
        $findme = "application";
        $pos = strpos($options, $findme);
        if ($pos === true) {
            echo $options;
    //echo $value->text->type->answer;
     //echo ($index. ' '. $options . '<br>');
        //echo current($value);
        }
    }

}

JSON:

{

    "question1": {
        "text": "What are the two types of permission lists that DSA concentrates on?",
        "type": "short_answer",
        "answer": {
                "1": "application", 
                "2": "row-level"
        }
    },
    "question2": {
        "text": "What are the building blocks for EmpowHR Security?",
        "type": "short_answer",
        "answer": {
                "1": "permission lists"
        }
    },
    "question3": {
        "text": "Who is the bomb?",
        "type": "short_answer",
        "answer": {
                "1": "permission"
        }
    }       
}
EN

回答 2

Stack Overflow用户

发布于 2020-03-23 09:01:18

使用给定的JSON文件测试以下内容。

重要提示:首先我将, true添加到$json = json_decode($myJSON); --> $json = json_decode($myJSON, true);这会将obj转换为数组

在回答json编码之后,我注意到在您试图解析的级别中有混合的字符串和数组类型,所以使用in_array()过滤掉字符串,并且只迭代数组,并且能够在该obj中找到当前构建中的“var_dumping”部分的所有实例。

代码语言:javascript
复制
$stmt = NULL;
$find = "application";
$myJSON = file_get_contents('quiz.json');
$json = json_decode($myJSON, true);

foreach( $json as $content ){
  foreach( $content as $target){
    if(is_array($target)){
      // we must find the key of the value within the next level of the array
      // and use it as index for the value $target to use in strpos() --> $target[$index]
      foreach($target as $index => $value){           
        if(strpos($target[$index], $find) !== false){
          $stmt = '<span>'.$target[$index].': CORRECT</span>';
        }
      }
    }    
  }
}

echo $stmt;
票数 1
EN

Stack Overflow用户

发布于 2020-03-23 06:07:28

代码语言:javascript
复制
foreach( $json as $question=>$content ){
   foreach( $content as $key=>$value ){
      if( strpos( $value, 'applikation' ) !== false
         echo $value;
      }
   }
}

strpos返回找到的位置,如果没有找到则返回false。

返回值=== true:始终为false

返回值== true:如果在第一个位置(0)上未找到或未找到,则返回false;如果在第一个位置之后找到,则返回true (所有数字!= 0均为true)

返回值!== false:正确的结果

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60805248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档