比较两个多维数组&获得差异&两个不同数组PHP中的唯一值

时间:2016-06-01 09:40:28

标签: php arrays multidimensional-array

我有两个多维数组......

$a1= Array
(
    [0] => Array
        (
            [sight_id] => 13
            [location] => Jodhpur, Rajasthan, India

        )

    [1] => Array
        (
            [sight_id] => 14
            [location] => Jodhpur Jn, Jodhpur, Rajasthan, India
                  )

    [2] => Array
        (
            [sight_id] => 15
            [location] => D-Kirtinagar, Jodhpur, Rajasthan, India

        )

   );


$a1= Array
(
    [0] => Array
        (
            [sight_id] => 13
            [location] => Jodhpur, Rajasthan, India

        )

    [1] => Array
        (
            [sight_id] => 14
            [location] => Jodhpur Jn, Jodhpur, Rajasthan, India
                  )

       [2] => Array
        (
            [sight_id] => 16
            [location] => Jaisalmer, Rajasthan, India

        )

    [3] => Array
        (
            [sight_id] => 17
            [location] => Fort Road, Amar Sagar Pol, Jaisalmer, Rajasthan, India

        ));

我想将给定数组分成三个不同的数组..

$intersect_array=Array
(
    [0] => Array
        (
            [sight_id] => 13
            [location] => Jodhpur, Rajasthan, India

        )

    [1] => Array
        (
            [sight_id] => 14
            [location] => Jodhpur Jn, Jodhpur, Rajasthan, India
                  ));

$only_a1=Array(
[0]=> Array
        (
            [sight_id] => 15
            [location] => D-Kirtinagar, Jodhpur, Rajasthan, India

        ));
$only_a2=Array(
[1] => Array
        (
            [sight_id] => 16
            [location] => Jaisalmer, Rajasthan, India

        )

    [2] => Array
        (
            [sight_id] => 17
            [location] => Fort Road, Amar Sagar Pol, Jaisalmer, Rajasthan, India

        ));

1 个答案:

答案 0 :(得分:1)

将数组转换为一种格式,其中数组索引是sight_id:

$b1 =array();
foreach($a1 as $x)
    $b1[$x['sight_id']] = $x['location'];

$b2 =array();
foreach($a2 as $x)
    $b2[$x['sight_id']] = $x['location'];

计算差异和交集:

$c_intersect = array_intersect_key($b1,$b2);
$c_1 = array_diff_key($b1,$b2);
$c_2 = array_diff_key($b2,$b1);

将数组转换回格式:

$intersect_array = array();
foreach($c_intersect as $i=>$v)
    $intersect_array[] = array('sight_id'=>$i,'location'=>$v);

$only_a1 = array();
foreach($c_1 as $i=>$v)
    $only_a1[] = array('sight_id'=>$i,'location'=>$v);

$only_a2 = array();
foreach($c_2 as $i=>$v)
    $only_a2[] = array('sight_id'=>$i,'location'=>$v);