如何在Object中搜索给定的字符串php

时间:2017-04-12 02:55:42

标签: php

我正在尝试为我的网站创建一个简单的php搜索。 我想在一个对象中搜索字符串的一部分。

$string_to_find = "hello";

这是对象

  0 => 
    object(stdClass)[1]
      public 'id' => int 1
      public 'name' => string 'John is hello'

  1 => 
    object(stdClass)[2]
      public 'id' => int 2
      public 'name' => string 'Hello people'
  2 => 
    object(stdClass)[2]
      public 'id' => int 3
      public 'name' => string 'yes people'

如何遍历此对象并返回一个对象(名称)为" hello"的对象。它不应该区分大小写。

所以如果它有效,那么0和1个obj应该是预期的行为吗?

我试过这样的事情:

$arr = array(); 
foreach($filesPopular as $k=>$v) { 
  if(strpos($string_to_find, $v)) {
      $arr[$k] = $v;
      $fileslike =  $arr[$k];
  }
} 

错误:无法将对象转换为int"

1 个答案:

答案 0 :(得分:1)

就像在评论中一样,只需使用foreachif

使用stripos,使其不区分大小写。确保您使用严格的比较!== false,如果stripos返回0,则会出现误报(因为认为零已经发现):

点子:

$string_to_find = "hello";
$contains_the_string = array(); // container of the matches
foreach ($filesPopular as $k => $v) { // so, for each object
    if (stripos($v->name, $string_to_find) !== false) {
    // check if string to find is contained within the name attribute
        $contains_the_string[] = $v; // if yes, put it inside the container
    }
} 
print_r($contains_the_string);
相关问题