如何相交多个多维数组

时间:2018-10-15 09:29:23

标签: php arrays multidimensional-array

我有两个不同的多维数组,如下所示:

Array //1st_array
(
    [0] => Array
        (
            [timestamp] => 7/10/2018 15:24:06
            [username] => giakhang
            [status] => 
        )

    [1] => Array
        (
            [timestamp] => 8/10/2018 5:11:25
            [username] => haophan
            [status] => 
        )

    [2] => Array
        (
            [timestamp] => 8/10/2018 6:38:18
            [username] => TTQ1504
            [status] => 
        )

    [3] => Array
        (
            [timestamp] => 08/10/2018 7:04:20
            [username] => btcgainer24724
            [status] => 
        )

)


Array //2nd_array
(
    [0] => Array
        (
            [timestamp] => 8/10/2018 5:10:06
            [username] => giakhang
        )

    [1] => Array
        (
            [timestamp] => 8/10/2018 5:13:25
            [username] => btcgainer24724
        )

    [2] => Array
        (
            [timestamp] => 8/10/2018 6:44:18
            [username] => anggie88
        )

    [3] => Array
        (
            [timestamp] => 08/10/2018 7:55:20
            [username] => ZeusTrade
        )

)

对于username1st_array之间的每个2nd_array,我希望将status1st_array中的unset从{{ 1}}对象未在以下两者之间相交:

2nd_array

如何与这些多维数组相交?

2 个答案:

答案 0 :(得分:1)

尝试一下:

foreach ($second_array as $key => $value) {
        $exist = false;
        foreach ($first_array as $key2 => $value2) {
            if ($value['username'] == $value2['username']) {
                $exist = true;
                $first_array[$key2]['status'] = 'Yes';
                break;
            } elseif (!$first_array[$key2]['status']) {
                $first_array[$key2]['status'] = 'No';
            }
        }

        if (!$exist) {

            unset($second_array[$key]);
        }
    }

答案 1 :(得分:0)

可能会有更清洁的解决方案,但这是我的尝试:

foreach ($1stArray as $1st) {
    foreach ($2ndArray as $2nd) {
        if ($1st['username'] == $2nd['username']) 
            $1st['status'] = 'Yes';
    }
    if (!$1st['status']) {
        $1st['status'] = 'No';
        unset($2ndArray[array_search($1st['username'], $1st)]);
    }
}

// Finally, we sanitize the 2ndArray indexes
$2ndArray = array_values($2ndArray);