比较两个数组并返回数组的差异

时间:2015-02-03 19:54:57

标签: php array-difference

我的旧数组数据:

[Job] => Array
        (
            [id] => 2
            [job_state_id] => 14
            [assigned_to_id] => 
            [patient_id] => 2
            [prescription] => main
            [case_type_id] => 1
            [upper_midline_id] => 1
            [upper_midline_value] => 0
            [lower_midline_id] => 1
            [lower_midline_value] => 0
            [treat_arches] => 2
            [upper_midline_type_id] => 2
            [lower_midline_type_id] => 2
            [overjet] => 2
            [overbite] => 2
            [arch_form] => 2
            [canine_relationship] => 2
            [molar_relationship] => 1
            [posterior_crossbite] => 1
            [procline] => 2
            [expand] => 2
            [distalize] => 0
            [ipr] => 0
            [close_all_spaces] => 2
            [other_instructions] => other

和我的新数组数据:

[Job] => Array
        (
            [id] => 2
            [job_state_id] => 14
            [assigned_to_id] => 
            [patient_id] => 2
            [prescription] => main complain
            [case_type_id] => 1
            [upper_midline_id] => 1
            [upper_midline_value] => 0
            [lower_midline_id] => 1
            [lower_midline_value] => 0
            [treat_arches] => 2
            [upper_midline_type_id] => 2
            [lower_midline_type_id] => 2
            [overjet] => 2
            [overbite] => 2
            [arch_form] => 2
            [canine_relationship] => 2
            [molar_relationship] => 1
            [posterior_crossbite] => 1
            [procline] => 2
            [expand] => 2
            [distalize] => 0
            [ipr] => 1
            [close_all_spaces] => 2
            [other_instructions] => other instrucations

你可以看到一些值是变化的。我需要将$ new数组数据与$ old数据数组进行比较,并仅捕获对该值所做的更改。 我使用了这段代码:

$difference = array_diff($oldJobData, $newJobData);

差异变量返回$oldJobData 我只希望差异不是整个数组 我也使用下面的代码,但不能得到欲望的结果。

          $new2 = array();
            foreach ($newJobData as $key => $new_val) {
                if (isset($oldJobData[$key])) { // belongs to old array?
                    if ($oldJobData[$key] != $new_val) // has changed?
                        $new2[$key] = $newJobData[$key]; // catch it
                }
            }

1 个答案:

答案 0 :(得分:2)

您有一个关联数组,因此必须使用array_diff_assoc

$changes = array_diff_assoc($new, $old);