我的第一个问题是,如何在对象数组 [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));
}
你可以为你的情况使用 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
试试array_intersect()
:
$output = array_intersect($array1, $array2);
print_r($output);