Show child results in parent array in Codeigniter

3

Good afternoon, I'm starting on Codeigniter and would like some help.

I have a Soccer Times table. Each team has its players that are in another table of my bank.

I get the values of these two separate tables, but I would like to create only one array that would organize each team with their respective players.

Example:

Times (
  [0] => Array
    (
        [id] => 1
        [time_name] => 'Barcelona'
    )

  [1] => Array
    (
        [id] => 2
        [time_name] => 'Real Madrid'
    )
 )

Jogadores (
    [0] => Array (
       [id] => 0
       [time_id] => 2
       [player_name] => 'Cristiano Ronaldo'
    )

    [1] => Array (
       [id] => 0
       [time_id] => 1
       [player_name] => 'Lionel Messi'
    )

So I would like to produce an array like this:

TimeCompleto (
    [0] => Array (
       [id] => 0
       [time_name] => 'Barcelona'
       Jogadores => Array (
           [1] => Array (
              [id] => 0
              [time_id] => 1
              [player_name] => 'Lionel Messi'
           )
       )
    )

Thanks for the help right away.

    
asked by anonymous 15.08.2017 / 15:45

1 answer

3

Work out as follows:

public function lista_times_jogadores(){
    $consulta = $this->db->get('times')->result();
    foreach($consulta as &$valor){
        $this->db->where('time_id', $valor->time_id);
        $valor->jogadores = $this->db->get('jogadores')->result();
    }
    return $consulta;
}

When you use the function next to the method, it returns array with subarrays.

[0] => Array (
   [id] => 0
   [time_name] => 'Barcelona'
   Jogadores => Array (
       [1] => Array (
          [id] => 0
          [time_id] => 1
          [player_name] => 'Lionel Messi'
       )
   )
)
    
15.08.2017 / 17:57