数组索引的PHP对象键值比较 [英] PHP object key value comparison of array indexes

查看:125
本文介绍了数组索引的PHP对象键值比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,两个数组的索引都包含对象

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"  
    }
}

我想比较$array2所有元素中$id键的值和$id_of每个$array1元素的值,如果不存在,则返回$array1元素.以下是我的代码,但不起作用

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;
    }

推荐答案

如果您将函数用作unanswered($array1,$array2),则在foreach循环中将$array1替换为$array2,反之亦然,或者通过unanswered($array2,$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

这篇关于数组索引的PHP对象键值比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆