cabita
cabita

Reputation: 852

Only last looped item is saved to a subarray while running nested loops

I have trying to build a dynamic multiarray, my code is the next:

$stud_data = array('estudiante1', 'estudiante2', 'estudiante3');
  $dates_data = array('date1', 'date2', 'date3');
  $stud_datan = count($stud_data);

  for ($i = 0; $i < $stud_datan; $i++) {
     $students[$i]['name'] = $stud_data[$i];
     for ($j = 0; $j < count($dates_data); $j++) {
         $dates[$i][$j] = $stud_data[$j];
         $students[$i]['dates'] = array($dates_data[$j] => $i . $j);
     }
  }

When I `print_r $students, I report the next array:

 Array (
       [0] => Array ( 
                [name] => estudiante1 
                [dates] => Array ( 
                         [date3] => 02 
                         ) 
                     ) 
       [1] => Array (  
                [name] => estudiante2  
                [dates] => Array (
                         [date3] => 12 
     
                         )
                    ) 

            )

but I want to build this structure, an array like this:

Array (
       [0] => Array ( 
                [name] => estudiante1 
                [dates] => Array ( 
                      [date1] => 01 
                      [date2] => 02 
                      [date3] => 03
                        )
                      ) 
       [1] => Array ( 
                [name] => estudiante2 
                [dates] => Array ( 
                      [date1] => 10 
                      [date2] => 11 
                      [date3] => 12 
                        )
                       ) 
      )
                      

What is my error? In the subarray dates only shows a value [date3], but not show [date1][date2].

Upvotes: 1

Views: 51

Answers (2)

cabita
cabita

Reputation: 852

This is the array with the structure that I wanted.

$stud_data=array('estudiante1','estudiante2','estudiante3');
  $dates_data=array('date1','date2','date3');
  $stud_datan=count($stud_data);

  for($i=0; $i<$stud_datan; $i++){
     $students[$i]['name']=$stud_data[$i];
     $students[$i]['dates'] = array();
     for ($j=0; $j < count($dates_data); $j++){
         $students[$i]['dates'][$dates_data[$j]] = $i.$j;
     }
  }

Upvotes: 0

mattacular
mattacular

Reputation: 1889

$stud_data=array('estudiante1','estudiante2','estudiante3');
  $dates_data=array('date1','date2','date3');
  $stud_datan=count($stud_data);

  for($i=0; $i<$stud_datan; $i++){
     $students[$i]['name']=$stud_data[$i];
     $students[$i]['dates'] = array();
     for ($j=0; $j < count($dates_data); $j++){
         $students[$i]['dates'][$j] = $stud_data[$j];
     }
  }

Upvotes: 3

Related Questions