合并不同长度的数组

时间:2013-09-03 19:21:32

标签: php arrays array-merge

给出以下格式的2个数组:

$array1 = array("1", "2", "3", "4", "5");

$array2 = array(
  0 => array("start" => "09:00", "end" => "17:00"),
  1 => array("start" => "18:00", "end" => "20:00")
);

我需要合并,结果是:

$result = array(
  array(
    "start_day" => "1",
    "start_time" => "09:00",
    "end_day" => "1",
    "end_time" => "17:00"
  ),
  array(
    "start_day" => "1",
    "start_time" => "18:00",
    "end_day" => "1",
    "end_time" => "20:00"
 )
 // and so on for each item in $array1
);

两个数组的长度可以不同,但​​$ array2中的每个项必须应用于$ array1中的项。把它扔到那里看看是否有人有这种合并的经验。我当前的解决方案只给了一个结果数组,其长度等于$ array2的长度。现在正在努力,但任何见解将不胜感激!

1 个答案:

答案 0 :(得分:1)

像这样:

$result = [];
foreach($array1 as $elem1) {
  foreach($array2 as $elem2) {
    $result[] = array(
      "start_day" => $elem1,
      "start_time" => $elem2['start'],
      "end_day" => $elem1,
      "end_time" => $elem2['end']
    );
  }
}