在多维对象数组中查找字符串的一部分

时间:2013-09-11 14:12:51

标签: php arrays object

我有这个对象数组:

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] => 
         ) 

但事实并非如此。只有我寻找'Dubbel Test'。 有没有人知道如何解决这个问题,所以我可以同时搜索字符串的一部分?

1 个答案:

答案 0 :(得分:3)

用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;
}

(未经测试,但应该有效)