简体   繁体   English

数组索引的PHP对象键值比较

[英]PHP object key value comparison of array indexes

I have two arrays where indexes of both arrays are contains objects我有两个数组,其中两个数组的索引都包含对象

$array1=array(1) { 
[0]=> object(stdClass) (3) {
    ["aid"]=> string(1) "1"
    ["a_number"]=> string(1) "0" 
    ["id_of"]=> string(1) "1"  
    }
}


$array2=array(3) { 
[0]=> object(stdClass) (3) {
    ["id"]=> string(1) "1",
    ["number"]=> string(1) "0" ,
    ["flag"]=> string(1) "1" , 
    ["zflag"]=> string(1) "0" , 
    ["xflag"]=> string(1) "1"  
    } ,
    [1]=> object(stdClass) (3) {
    ["id"]=> string(1) "2",
    ["number"]=> string(1) "2" ,
    ["flag"]=> string(1) "2" , 
    ["zflag"]=> string(1) "0" , 
    ["xflag"]=> string(1) "1"  
    },
    [1]=> object(stdClass) (3) {
    ["id"]=> string(1) "3",
    ["number"]=> string(1) "3", 
    ["flag"]=> string(1) "3" , 
    ["zflag"]=> string(1) "0" , 
    ["xflag"]=> string(1) "1"  
    }
}

I want to compare between the value of $id key in all elements of $array2 with the value of $id_of each element of $array1 , if it's not exist then return the element of $array1 .我想将$array2所有元素中的$id键的值与$id_of每个元素的$array1 $id_of的值进行$id_of ,如果它不存在则返回$array1的元素。 Below is my code but it doesn't work下面是我的代码,但它不起作用

public function unanswered($array1,$array2){
        if(!(empty($array2))){
            $unanswered_arrays=array();
            foreach($array1 as $b){
                foreach($array2 as $a){
                    if($b->id != $a->id_of){
                        array_push($unanswered_arrays,(object)$b);
                    }
                }
            }
            return $unanswered_arrays;
        }
        return $array1;
    }

If you're using your function as unanswered($array1,$array2) then replace $array1 with $array2 and vice versa in foreach loops or pass unanswered($array2,$array1) instead of.如果您使用的是unanswered($array1,$array2)函数unanswered($array1,$array2)则在 foreach 循环中将$array1替换$array1 $array2 ,反之亦然,或者传递unanswered($array2,$array1)而不是。

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM