1

1つの文字列を検索して関連する値を取得したいのですが、関数のテストでは、毎回単語(TitleOr WouldOr PostOr Ask)を検索して1つの出力のみを表示(提供)しますTitle,11,11!!!! どうすれば修正できますか?

  // test array
  $arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
  // define search function that you pass an array and a search string to
  function search($needle,$haystack){
    //loop over each passed in array element
    foreach($haystack as $v){
      // if there is a match at the first position
      if(strpos($needle,$v) == 0)
        // return the current array element
        return $v;
    }
    // otherwise retur false if not found
    return false;
  }
  // test the function
  echo search("Would",$arr);
4

3 に答える 3

1

問題はにありますstrposhttp://php.net/manual/en/function.strpos.php
haystackが最初の引数で、2番目の引数が針です。0を取得するための比較
も行う必要があります。===

// test array
$arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
// define search function that you pass an array and a search string to
function search($needle,$haystack){
  //loop over each passed in array element
  foreach($haystack as $v){
    // if there is a match at the first position
    if(strpos($v,$needle) === 0)
      // return the current array element
      return $v;
  }
  // otherwise retur false if not found
  return false;
}
// test the function
echo search("Would",$arr);
于 2011-09-19T06:09:16.497 に答える
0

この関数はブール値のFALSEを返す場合がありますが、0や""などのFALSEと評価される非ブール値を返す場合もあります。詳細については、ブール値のセクションをお読みください。この関数の戻り値をテストするには、===演算子を使用します。

ソース: http: //php.net/strpos

于 2011-09-19T06:05:39.120 に答える
0

このチェックを変更します。

// if there is a match at the first position
if(strpos($needle,$v) == 0)
  // return the current array element
  return $v;

// if there is a match at the first position
if(strpos($needle,$v) === 0)
  return $v;

また

// if there is a match anywhere
if(strpos($needle,$v) !== false)
  return $v;

文字列が見つからない場合、strposはfalseを返しますfalse == 0が、phpは。として扱わ0れるため、チェックするとtrueになりfalseます。これを防ぐには、===演算子を使用する必要があります(または!==、正確に何をしようとしているのかによっては)。

于 2011-09-19T06:05:59.933 に答える