【问题标题】:Detect the difference between two arrays using laravel使用 laravel 检测两个数组之间的差异
【发布时间】:2017-04-11 15:18:33
【问题描述】:

我有两个数组,我需要验证它们之间的不同之处,例如:
数组 A 中存在某些东西,但 B 中不存在,
与 B 相比,数组 A 中的一个参数是不同的......

$temp = import_temp::select('cod_disciplina', 'cod_turma', 'hr_inicio', 'hr_fim', 'dia_semana')->get();
        $turmas;
        foreach($temp as $t)
        {
           $turmas = Horario::select('cod_disciplina', 'cod_turma', 'hr_inicio', 'hr_fim', 'dia_semana')
            ->whereIn('cod_disciplina', $temp->lists('cod_disciplina'))
            ->whereIn('cod_turma', $temp->lists('cod_turma'))
            ->where('ano_semestre', $ano_semestre)->get();
        }

当我这样做时:

 print_r($turmas->toArray()); 
 print_r($temp->toArray());   

我得到:

我如何比较这些键并确定 changednew 还是 missing

尝试使用array_diff_assoc,但出现以下错误:

数组到字符串的转换

array_diff_assoc($temp->toArray(),   $turmas->toArray());  

也试过This that I found in another answer in a similar question,但没用。

【问题讨论】:

    标签: php arrays laravel associative-array


    【解决方案1】:

    首先定义你自己的函数来比较数组:

    function arrayCmp($a, $b) {
        if ($a < $b) {
            return -1;
        } elseif ($a > $b) {
            return 1;
        } else {
            return 0;
        }
    }
    

    然后,如果您想要 $a bot 中存在的元素而不是 $b 中的元素,那么您调用:

    $diff = array_udiff($a, $b, 'arrayCmp');
    

    【讨论】:

    • 如果我同时拥有所有元素,但其中一个或多个元素具有不同的值怎么办?
    • 你说的很矛盾。如果某些元素具有不同的值,则它们是不同的元素,不能同时在两者中。
    猜你喜欢
    • 1970-01-01
    • 2019-05-02
    • 2013-08-05
    • 1970-01-01
    • 2020-01-19
    • 2021-04-27
    • 2013-06-18
    • 2012-12-20
    • 2018-07-17
    相关资源
    最近更新 更多