dqyat62284 2016-05-20 11:30 采纳率: 0%
浏览 17
已采纳

php - 比较和提取常见的数组元素

I have been trying to compare values of inner arrays from a multidimensional array and extract those common values into another array. I have tried using array_intersect along with a foreach loop but this is not giving me result, here the number of inner arrays is dynamic and generated from a different function. Have anyone tried before comparing array elements of a multidimensional array?

My Array:

    $days_filter = array(
    [0] => array(
        '00:00',
        '01:30',
        '02:30',
    ),
    [1] => array(
        '00:00',
        '01:30',
        '03:30',
    ),
    [2] => array(
        '00:30',
        '01:30',
        '02:30',
    ),
    [3] => array(
        '00:30',
        '01:30',
        '04:30',
    ),
);

$res_arr = $days_filter[0];
foreach ($days_filter as $filter) {
    $res_arr = array_intersect($res_arr, $filter);
}

Expected output array:

$res_arr = array(
    [0]=>'01:30'
)

because 01:30 is the common element of all inner arrays.

  • 写回答

4条回答 默认 最新

  • dongwubao4785 2016-05-20 11:51
    关注

    array_intersect() works for you..

    $days_filter = array(
        0 => array(
            '00:00',
            '01:30',
            '02:30',
        ),
        1 => array(
            '00:00',
            '01:30',
            '03:30',
        ),
        2 => array(
            '00:30',
            '01:30',
            '02:30',
        ),
        3 => array(
            '00:30',
            '01:30',
            '04:30',
        ),
    );
    $first = $days_filter[0];
    
    for($i=1; $i<count($days_filter); $i++)
    {
      $result = array_intersect($first, $days_filter[$i]);
      $first = $result;
    }
    
    print_r($result);
    

    This will give you :

    Array
    (
        [1] => 01:30
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?