比较关联数组值并返回不同的值


Compare the associative array values and return the different values

>我在下面有一个这样的关联数组:

<?php 
    $first = array(
        array('lastexam' => '170220', 'nextexam' => '170220', 'phone' => '170220', 'fax' => '170220'),
        array('lastexam' => '170220', 'nextexam' => '170220', 'phone' => '170220', 'fax' => '170220'),
        array('lastexam' => '170221', 'nextexam' => '170220', 'phone' => '170224', 'fax' => '170220'),
        array('lastexam' => '170221', 'nextexam' => '170226', 'phone' => '170220', 'fax' => '170220'),
        array('lastexam' => '170222', 'nextexam' => '170220', 'phone' => '170225', 'fax' => '170220')
    ); 
?>

我需要比较$first[0]$first[1]$first[1]$first[2]$first[2]$first[3]$first[3]$first[4]。我需要得到如下结果:

例如:

<?php
array
(
  [2] => array
  (
     [lastexam] => 170221,
     [phone] => 170224,
  ),
  [3] => array
  (
     [nextexam] => 170226,
     [phone] => 170220,
  ),
  [4] => array
  (
     [lastexam] => 170222,
     [phone] => 170225,
  )
);
?>

我认为这将解决您的问题

<?php 
    $first = array(
        array('lastexam' => '170220', 'nextexam' => '170220', 'phone' => '170220', 'fax' => '170220'),
        array('lastexam' => '170220', 'nextexam' => '170220', 'phone' => '170220', 'fax' => '170220'),
        array('lastexam' => '170221', 'nextexam' => '170220', 'phone' => '170224', 'fax' => '170220'),
        array('lastexam' => '170221', 'nextexam' => '170226', 'phone' => '170220', 'fax' => '170220'),
        array('lastexam' => '170222', 'nextexam' => '170220', 'phone' => '170225', 'fax' => '170220')
        );
    $pre = array();
    $cur = array();
    $tmp = array();
    echo '<pre>'; print_r($first); echo '</pre>';
    foreach($first as $key => $val) {
        foreach ($val as $key1 => $val1) {
            $cur[$key1] = $val1;
            if (isset($pre[$key1]) && $pre[$key1] !== $cur[$key1]) {
                $tmp[$key][$key1] = $val1;
            }
            $pre[$key1] = $val1;
        }
    }
    echo '<pre>'; print_r($tmp); echo '</pre>';
    ?>

如果是这样,请在下面点赞或评论

我发现按照布拉德·肯特在评论中的建议使用array_diff要干净得多。

$result = [];
for ($i = count($first)-1; $i >= 1; $i--) {
    $diff = array_diff($first[$i], $first[$i-1]);
    if (!empty($diff))
        $result[$i] = $diff;
}

这是您要搜索的一点点吗?

     $first = array(
        array('lastexam' => '170220', 'nextexam' => '170220', 'phone' => '170220', 'fax' => '170220'),
        array('lastexam' => '170220', 'nextexam' => '170220', 'phone' => '170220', 'fax' => '170220'),
        array('lastexam' => '170221', 'nextexam' => '170220', 'phone' => '170224', 'fax' => '170220')
        ); 

    if((array_values($first)[0]['lastexam']) == (array_values($first)[1]['lastexam'])){
        var_dump(array_values($first)[2]['lastexam']);
        var_dump(array_values($first)[2]['phone']);
    } else {
        //
        echo "whatever..." ;
        //
    }

?? 还不完美,因为我没有掌握你想要实现的整体画面。但是有了这个if语句,你至少可以比较你想要比较的内容。祝你好运!。