4

我的第一个问题是,如何在对象数组 [words] 中搜索我的数组的值并在找到匹配项时返回对象?

如何寻找更好的匹配?在下面的示例中,第二个对象与 2 个共同的单词匹配得更好,而不是第一个对象只有 1 个匹配。

Array
(
    [0] => blue
    [1] => green
    [2] => love
    [3] => sandro
)


stdClass Object
(
    [1] => stdClass Object
        (
            [words] => Array
                (
                    [0] => green
                    [1] => blue
                )

            [html] => html+img+link+code
        )

    [2] => stdClass Object
        (
            [words] => Array
                (
                    [0] => love
                    [1] => sex
                    [2] => blue
                )

            [html] => html+img+link+code
        )

)

我试过的代码:

foreach ($ads_arr as $ad) {
  print_r(array_intersect($ad->words,$words_arr));
}
4

2 回答 2

1

您可以为您的案例使用for循环,但您应该考虑定义真正的 php 类(不是stdClass)并实现一些方法来帮助您。

foreach($main_std as $id => $sub_std){
 $count_match[$id] = 0;
 // now, check for each objects 
 // you can use an other loop with in_array, array_intersect 
 // or any other way
 foreach($the_array as $word_search)
 {
   // for each word you're looking for, add +1
   if (in_array($word_search, $sub_std->words))
     $count_match[$id] ++;
 }
}
// here, $count_match is an array you can sort by best match or whatever you want
于 2013-11-02T09:10:46.323 回答
0

试试看array_intersect()

$output = array_intersect($array1, $array2);
print_r($output);
于 2013-11-02T08:51:30.490 回答