比较两个多维数组并将结果输出到新数组中

时间:2019-02-12 12:00:21

标签: php arrays multidimensional-array

我有两个数组:

Array 
( 
    [0] => Array 
        ( 
            [passers] => 6423 
            [gdat] => 2019-02-06 
        ) 
    [1] => Array 
        ( 
            [passers] => 9700
            [gdat] => 2019-02-07 
        ) 
    [2] => Array 
        ( 
            [passers] => 12559
            [gdat] => 2019-02-08 
        )
)

Array 
( 
    [0] => Array 
        ( 
            [passers] => 6423 
            [gdat] => 2019-02-06 
        ) 
    [1] => Array 
        ( 
            [passers] => 9604 
            [gdat] => 2019-02-07 
        ) 
    [2] => Array 
        ( 
            [passers] => 11559 
            [gdat] => 2019-02-08 
        )
)

第一个数组中[passers]的值将始终大于第二个数组中的值,对于[gdat],两个数组中的值始终相同。

我需要比较两个[passers]的值并将结果输出到新数组中:

Array 
( 
    [0] => Array 
        ( 
            [passers] => 0
            [gdat] => 2019-02-06 
        ) 
    [1] => Array 
        ( 
            [passers] => 96
            [gdat] => 2019-02-07 
        ) 
    [2] => Array 
        ( 
            [passers] => 1000
            [gdat] => 2019-02-08 
        )
)

2 个答案:

答案 0 :(得分:1)

如果问题中显示的是一对一的对应关系,则可以循环遍历array1并从array2中减去值:

$array3 = array();
foreach ($array1 as $key => $value) {
    $array3[$key]['passers'] = $value['passers'] - $array2[$key]['passers'];
    $array3[$key]['gdat'] = $value['gdat'];
}

如果array2中的键不一定与array1中的键相对应,则可以使用array_search为给定的gdat值找到正确的键:

$array4 = array();
foreach ($array1 as $key => $value) {
    $key2 = array_search($value['gdat'], array_column($array2, 'gdat'));
    $array4[$key]['passers'] = $value['passers'] - $array2[$key2]['passers'];
    $array4[$key]['gdat'] = $value['gdat'];
}

对于您的样本数据,两者的结果相同:

Array 
( 
    [0] => Array 
        ( 
            [passers] => 0
            [gdat] => 2019-02-06 
        ) 
    [1] => Array 
        ( 
            [passers] => 96
            [gdat] => 2019-02-07 
        ) 
    [2] => Array 
        ( 
            [passers] => 1000
            [gdat] => 2019-02-08 
        )
)

Demo on 3v4l.org

答案 1 :(得分:0)

将数组1放入$array1,将数组2放入$array2,结果放入$result

$result = [][];
foreach($array1 as $i => $a)
{
  // To avoid négative number we call absolute function
  $result[$i]['passers'] = abs($a['passers'] - $array2[$i]['passers']); 
  $result[$i]['gdat'] = $a['gdat'];
}
var_dump($result);