排序和合并关联数组(PHP)

时间:2015-09-23 07:59:08

标签: php associative-array

我有2个关联数组:

[0] => Array (
    [time] => 09:00:00
    [name] => To do something 1
    )
[1] => Array (
    [time] => 09:30:00
    [name] => To do something 2
    )
[2] => Array (
    [time] => 10:00:00
    [name] => To do something 3
    )

[0] => Array (
    [time] => 09:00:00
    )
[1] => Array (
    [time] => 09:15:00
    )
[2] => Array (
    [time] => 09:30:00
    )
[3] => Array (
    [time] => 09:45:00
    )
[4] => Array (
    [time] => 10:00:00
    )

需要做另一个关联数组:

  • 如果第二个数组中的字段[time]等于第一个数组中的field [time],则添加[name];
  • 如果第二个数组中的field [time]不等于第一个数组中的field [time],则添加空[name]。

应该是这样的:

[0] => Array (
    [time] => 09:00:00
    [name] => To do something 1
    )
[1] => Array (
    [time] => 09:15:00
    [name] => 
    )
[2] => Array (
    [time] => 09:30:00
    [name] => To do something 2
    )
[3] => Array (
    [time] => 09:45:00
    [name] => 
    )
[4] => Array (
    [time] => 10:00:00
    [name] => To do something 3
    )

1 个答案:

答案 0 :(得分:1)

经过一番困惑,我觉得它适合你。

这是您可以使用的代码:

$array3 = array();

foreach ($array2 as $key2 => $value2){
    $found = false;

    foreach ($array1 as $key1 => $value1){
        if ($array1[$key2]['time'] == $array2[$key2]['time']) {
            $array3[$key2]['time']  = $array1[$key1]['time'];
            $array3[$key2]['name'] = $array1[$key1]['name'];
            $found = true;
        }
    }
    if (!$found){
        //add
        $array3[$key2]['time']  = $array2[$key2]['time'];
        $array3[$key2]['name'] = "";

    }
}

print_r($array3);