2016-10-17 89 views
0

我有兩個陣列:映射兩個數組到具有n×m個元件的一個陣列

Array1 
(
    [0] => Mon 
    [1] => Tue 
    [2] => Wed 
    [3] => Thu 
) 
Array2 
(
    [0] => 12:00 am,04:00 pm 
    [1] => 07:00 am,02:00 pm 
) 

我需要的結果陣列是這樣的:

(
      [startTime] => Array 
       (
        [hours] => 07 
        [minutes] => 00 am 
       ) 

      [endTime] => Array 
       (
        [hours] => 02 
        [minutes] => 00 pm 
       ) 
      [weekday] => Monday 
     ) 

在理想情況下,將有4 * 2 =新陣列中的8個元素。我得到8,但沒有得到正確的數據。

這裏是我的代碼:

$j = 0; 
     foreach($array2 as $key => $value) { 
      $start_time = explode(',', $value)[0]; 
      if(!empty($start_time)) { 
       $end_time = explode(',', $value)[1]; 
       $gen_timings_array[$j]['startTime']['hours'] = explode(':',$start_time)[0]; 
       $gen_timings_array[$j]['startTime']['minutes'] = explode(':',$start_time)[1]; 
       $gen_timings_array[$j]['endTime']['hours'] = explode(':',$end_time)[0]; 
       $gen_timings_array[$j]['endTime']['minutes'] = explode(':',$end_time)[1]; 

       foreach ($array1 as $key => $value) { 
        $gen_timings_array[$j]['weekday'] = $enum[$value]; 
        ++$j; 
       } 
      } 
     } 

這是我得到的輸出:

Array 
(
    [0] => Array 
     (
      [startTime] => Array 
       (
        [hours] => 12 
        [minutes] => 00 am 
       ) 

      [endTime] => Array 
       (
        [hours] => 04 
        [minutes] => 00 pm 
       ) 
      [weekday] => Monday 
     ) 

    [1] => Array 
     (
      [weekday] => Tuesday 
     ) 

    [2] => Array 
     (
      [weekday] => Wednesday 
     ) 

    [3] => Array 
     (
      [weekday] => Thursday 
     ) 

    [4] => Array 
     (
      [startTime] => Array 
       (
        [hours] => 07 
        [minutes] => 00 am 
       ) 

      [endTime] => Array 
       (
        [hours] => 02 
        [minutes] => 00 pm 
       ) 
      [weekday] => Monday 
     ) 

    [5] => Array 
     (
      [weekday] => Tuesday 
     ) 

    [6] => Array 
     (
      [weekday] => Wednesday 
     ) 

    [7] => Array 
     (
      [weekday] => Thursday 
     ) 

) 

回答

0

這個怎麼樣:

$j = 0; 
foreach($array2 as $key => $value) { 
    $start_time = explode(',', $value)[0]; 
    if(!empty($start_time)) { 
     $end_time = explode(',', $value)[1]; 

     foreach ($array1 as $key => $value) { 
      $gen_timings_array[$j]['startTime']['hours'] = explode(':',$start_time)[0]; 
      $gen_timings_array[$j]['startTime']['minutes'] = explode(':',$start_time)[1]; 
      $gen_timings_array[$j]['endTime']['hours'] = explode(':',$end_time)[0]; 
      $gen_timings_array[$j]['endTime']['minutes'] = explode(':',$end_time)[1]; 

      $gen_timings_array[$j]['weekday'] = $enum[$value]; 
      ++$j; 
     } 
    } 
}