1

我有这个对象数组:

stdClass Object (
   [ReadOpenCallsResult] => stdClass Object (
      [CallHeader] => Array (
         [0] => stdClass Object ( 
            [DateChanged] => 0001-01-01T00:00:00 
            [DateCreated] => 2013-09-11T15:53:39.773 
            [Description] => Dubbel Test 
            [MessageCode] => C0000453325 
            [MessageId] => 83656 
            [Solved] => 
         ) 
         [1] => stdClass Object ( 
            [DateChanged] => 0001-01-01T00:00:00 
            [DateCreated] => 2013-09-11T13:40:54.077 
            [Description] => Test 
            [MessageCode] => C0000453324 
            [MessageId] => 83653 
            [Solved] => 
         ) 
      ) 
   ) 
)

我有一个函数可以在这个数组中查找一个字符串:

function in_object($val, $obj){
    if($val == ""){
        trigger_error("in_object expects parameter 1 must not empty", E_USER_WARNING);
        return false;
    }
    if(!is_object($obj)){
        $obj = (object)$obj;
    }

    foreach($obj as $key => $value){
        if(!is_object($value) && !is_array($value)){
            if($value == $val){
                return true;
            }
        }
        else{
            return in_object($val, $value);
        }
    }
    return false;
}

现在,这个函数看起来非常适合完整的字符串。例如,如果我搜索“测试”,它会返回这部分;

[1] => stdClass Object ( 
            [DateChanged] => 0001-01-01T00:00:00 
            [DateCreated] => 2013-09-11T13:40:54.077 
            [Description] => Test 
            [MessageCode] => C0000453324 
            [MessageId] => 83653 
            [Solved] => 
         ) 

但是,如果我寻找“Dubbel”的例子,我希望该函数返回我:

[0] => stdClass Object ( 
            [DateChanged] => 0001-01-01T00:00:00 
            [DateCreated] => 2013-09-11T15:53:39.773 
            [Description] => Dubbel Test 
            [MessageCode] => C0000453325 
            [MessageId] => 83656 
            [Solved] => 
         ) 

但事实并非如此。只有当我寻找“杜贝尔测试”时。有谁知道如何解决这个问题,所以我可以同时搜索字符串的一部分?

4

1 回答 1

4

用 strpos() 替换您的 ==,如下所示:

function in_object($val, $obj){
if($val == ""){
    trigger_error("in_object expects parameter 1 must not empty", E_USER_WARNING);
    return false;
}
if(!is_object($obj)){
    $obj = (object)$obj;
}

foreach($obj as $key => $value){
    if(!is_object($value) && !is_array($value)){
        if(strpos($value,$val)!==FALSE){
            return true;
        }
    }
    else{
        return in_object($val, $value);
    }
}
return false;
}

(未经测试,但应该可以工作)

于 2013-09-11T14:19:52.370 回答