2015-09-23 307 views
3

我有2個關聯數組:排序和合並關聯數組(PHP)

[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 
    ) 

需要做另一個關聯數組:

  • 如果字段[時間]在第二個數組中等於第一個數組中的字段[時間],然後添加[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

一些莫名其妙的我讓他爲你工作之後。

這是你可以使用代碼:

$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); 
+0

遺憾的是它不工作,但只顯示一個數組中的最後一條記錄[名]和陣列秀等元素與空[名]鍵,但我理解你的想法。謝謝。 –