0

所以我试图检查这个数组是否有下划线。我不确定我是否使用了正确的功能来执行此操作。任何输入将不胜感激。

更多信息,如果数组确实有下划线,我希望它运行下面的代码。这段代码分开并给了我我想要的属性。我还检查它是否有和 S 然后运行一些代码。这些都是查询的输出,然后在最后进行查询。

    if (count($h)==3){
           if (strpos($h[2], '_') !== false)  // test to see if this is a weird quiestion ID with an underscore
               {
                    if (strpos($h[2], 'S') !== false)
                    {
                     // it has an S
                     $underscoreLocation = strpos($h[2], '_');
                     $parent = substr($h[2], 0, $underscoreLocation - 6); // start at beginning and go to S
                     $title = substr($h[2], $underscoreLocation - 5, 5);
                     $questions = "select question from lime_questions where sid =".$h[0]." and gid =".$h[1]." and parent_qid =".$parent." and title =".$title.";";
                    }
                    else
                    {
                     // there is no S
                     $underscoreLocation = strpos($h[2], '_');
                     $parent = substr($h[2], 0, $underscoreLocation - 2);
                     $title = substr($h[2], $underscoreLocation - 1, 1);
                     $questions = "select question from lime_questions where sid =".$h[0]." and gid =".$h[1]." and parent_qid =".$parent." and title =".$title.";";
                    }    
               }

           else
           {
            $questions = "select question from lime_questions where sid =".$h[0]." and gid =".$h[1]." and qid =".$h[2].";";
           }
4

1 回答 1

1

当检查字符串中是否存在子字符串时,strpos() 是一个很好的函数,所以你的基本前提是好的。

您提交给 strpos() 的干草堆(即 $h[2])是一个字符串,不是吗?您在问题中说您正在检查数组是否包含下划线,但代码仅检查单个数组项是否包含下划线 - 这是两个非常不同的事情。

如果 $h[2] 是一个子数组,而不仅仅是 $h 数组中的一个字符串,那么您需要遍历子数组并检查每个项目。

所以:

  for ($x=0; $x<count($h[2]); $x++) {
     if (strpos($h[2][$x], "_")!==false) {
         if (strpos($h[2][$x], 'S') !== false) {
            // Run code
         } else { 
            // Run code
         }
     }
  }

如果 $h[2] 只是一个字符串,那么你所拥有的应该没问题。


更新:尝试添加

print($h[2][$x].' - '.strpos($h[2][$x], ''));

之前上线

print ($h[2][$x].' - '.strpos($h[2][$x], '')); 

这应该让我们了解问题所在。


更新:

根据我们刚刚运行的代码,事情与我的想法有很大不同。首先,并非所有返回的 $h 数组都有 3 个项目。其次 $h2 是一个搅拌,而不是一个子数组。

所以这是新代码:

  if (count($h)==3) {
     print($h2.' | ');
     if (strpos($h[2], "_")!==false) {
         print(' underscore was found | ');
         if (strpos($h[2], 'S') !== false) {
            // Run code
         } else { 
            // Run code
         }
     }
  } else {
     // array does not represent a question
  }

Also, you need to change all of the $h[2][$x] back to just $h[2]. Tell me how it goes.

于 2012-11-28T21:29:12.453 回答