Question

Given 2 arrays of the following formats:

$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")
);

I need to merge so that the result is:

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

Both arrays can be of varying lengths but each item in $array2 must be applied to an item in $array1. Just throwing this out there to see if anyone has any experience with this sort of merge. My current solution only gives me a result array with a length that equals the length of $array2. Working on this now but any insight would be appreciated!

Était-ce utile?

La solution

Like this:

$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']
    );
  }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top