多维数组差分 php

2022-08-31 00:13:33

我有两个多维数组,我想要差异。例如。我在下面采用了二维二维数组

$array1 = Array (
       [a1] => Array  (
          [a_name] => aaaaa
          [a_value] => aaa
     )

       [b1] => Array (
          [b_name] => bbbbb
          [b_value] => bbb
   )
       [c1] => Array (
          [c_name] => ccccc
          [c_value] => ccc
   )

)

$array2 = Array (
 [b1] => Array (
       [b_name]=> zzzzz
     )
)

现在我想要这两个数组的关键区别。我尝试过array_diff_key(),但它不适用于多维。

array_diff_key($array1, $array2)

我想要如下输出

//output
$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
 )

   [b1] => Array (          
      [b_value] => bbb
)
   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
)

)

如果您认为我的问题是真实的,请接受并回答。谢谢。

编辑

现在,如果第二个数组是

$array2 = Array( [b1] => zzzzz)

结果应该是

$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
    )     

   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
     )

)

答案 1

请检查我是否正确理解您,然后此代码片段可以帮助您解决问题。我已针对您指定的问题对其进行了测试。如果要为其运行其他测试用例,可以告诉我调整代码。

$a1 = array(
    'a1' => array('a_name' => 'aaa', 'a_value' => 'aaaaa'),
    'b1' => array('b_name' => 'bbb', 'b_value' => 'bbbbbb'),
    'c1' => array('c_name' => 'ccc', 'c_value' => 'cccccc')
);

$a2 = array(
    'b1' => array('b_name' => 'zzzzz'),
);

$result = check_diff_multi($a1, $a2);
print '<pre>';
print_r($result);
print '</pre>';


function check_diff_multi($array1, $array2){
    $result = array();
    foreach($array1 as $key => $val) {
         if(isset($array2[$key])){
           if(is_array($val) && $array2[$key]){
               $result[$key] = check_diff_multi($val, $array2[$key]);
           }
       } else {
           $result[$key] = $val;
       }
    }

    return $result;
}

编辑:添加了对代码的调整。


答案 2

这个解决方案啊对我很有帮助,我希望可以帮助他们做点什么,不管是什么阵列都处于混乱状态。

function your_array_diff($arraya, $arrayb) {

    foreach ($arraya as $keya => $valuea) {
        if (in_array($valuea, $arrayb)) {
            unset($arraya[$keya]);
        }
    }
    return $arraya;
}

$a1 = Array
    (
    "0" => Array
        (
        "Empresa" => "TMC01",
        "Paga" => "13/01/2015",
        "ID" => "M2",
        "Valor" => "200",
        "Nombre" => "BONI"
    ),

    "1" => Array
        (
        "Empresa" => "TMC01",
        "Paga" => "13/01/2015",
        "ID" => "M1",
        "Valor" => "100",
        "Nombre" => "SUELDO"
    )
);

$b1 = Array
    (
    "0" => Array
        (
        "Empresa" => "TMC01",
        "Paga" => "13/01/2015",
        "ID" => "M1",
        "Valor" => "100",
        "Nombre" => "SUELDO"
    ),
    "1" => Array
        (
        "Empresa" => "TMC01",
        "Paga" => "13/01/2015",
        "ID" => "M2",
        "Valor" => "200",
        "Nombre" => "BONI"
    )
);

$resultado = your_array_diff($a1, $b1);

echo "<pre>";
echo print_r($resultado);
echo "</pre>";

推荐