简体   繁体   中英

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 . 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.

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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