Show results children in parent array in Codeigniter

Asked

Viewed 47 times

3

Good afternoon, I’m starting at Codeigniter and would like a help.

I have a table of football teams. Each team has its players who are in another table of my bench.

I receive the values of these two separate tables, but would like to create only one array that organizes 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'
    )

Then I would like to produce an array this way:

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

Thanks in advance for the help.

1 answer

3


Elaborate 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 will return array with subarrays.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.