Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...