Php 对象数组的数组相交
我有两个包含友元对象的数组。我想找到相互匹配的ID以实现“共同的朋友”功能。如果使用PHP太复杂,也许我会用mysql的方式 以下是示例数组项:Php 对象数组的数组相交,php,Php,我有两个包含友元对象的数组。我想找到相互匹配的ID以实现“共同的朋友”功能。如果使用PHP太复杂,也许我会用mysql的方式 以下是示例数组项: $array1 = array(1) { ["friends_list"]=> array(3) { [0]=> object(stdClass)#29 (8) { ["notifica_ID"]=> string(4) "2673" } [1]=> object(stdClass)#30 (8) { ["notif
$array1 = array(1) {
["friends_list"]=>
array(3) {
[0]=>
object(stdClass)#29 (8) {
["notifica_ID"]=>
string(4) "2673"
}
[1]=>
object(stdClass)#30 (8) {
["notifica_ID"]=>
string(4) "3532"
}
[2]=>
object(stdClass)#31 (8) {
["notifica_ID"]=>
string(4) "3649"
}
}
}
$array2 = array(1) {
["friends_list"]=>
array(5) {
[0]=>
object(stdClass)#32 (8) {
["notifica_ID"]=>
string(4) "1679"
}
[1]=>
object(stdClass)#33 (8) {
["notifica_ID"]=>
string(4) "2137"
}
[2]=>
object(stdClass)#35 (8) {
["notifica_ID"]=>
string(4) "3186"
}
[3]=>
object(stdClass)#36 (8) {
["notifica_ID"]=>
string(4) "3187"
}
[4]=>
object(stdClass)#37 (8) {
["notifica_ID"]=>
string(4) "3649"
}
}
}
我希望结果是:
$result = array(1) {
["friends_list"]=>
array(1) {
[0]=>
array(
["notifica_ID"]=>
string(4) "3649"
)
}
}
我已经尝试了
array\u intersect
方法,但我不知道如何在对象数组中实现它。不是简单的解决方案,但这会起作用
$new_array1 = obj_to_array( $array1["friends_list"] );
$new_array2 = obj_to_array( $array2["friends_list"] );
$temp_result = array_uintersect( $new_array1, $new_array2, 'compare_values' );
$result = array( "friends_list" => $temp_result );
function obj_to_array( $input1 )
{
foreach( $input1 as $new )
$temp_array[] = (array)$new;
return $temp_array;
}
function compare_values($input1, $input2)
{
return strcmp($input1['notifica_ID'], $input2['notifica_ID']);
}
$result
正是您所期望的。我决定将id放入其他数组中。然后执行array\u intersect
方法。
这就是我现在的答案
public function mutual_friends($my_ID = '' ,$friend_ID = ''){
if($friend_ID != '' OR $my_ID != ''){
$myfr = $this->get_friends($my_ID);
$frofmy = $this->get_friends($friend_ID);
$array1 = array();
$array2 = array();
foreach($myfr['friends_list'] as $row){
$array1[] = $row->notifica_ID;
}
foreach($frofmy['friends_list'] as $row){
$array2[] = $row->notifica_ID;
}
$result = array_intersect($array1,$array2);
if(count($result) > 0){
$mf = array();
$i = 0;
foreach($myfr['friends_list'] as $row){
foreach($result as $row1){
if($row1 == $row->notifica_ID){
$mf[$i]['notifica_ID'] = $row->notifica_ID;
$i++;
}
}
}
return $mf;
}
else{
return false;
}
}else{
return false;
}
}
@戴夫,我为我的错误句子感到抱歉。没必要道歉。这是一个旨在改进问答的社区。