Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
198 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...