如何从数据库中获取数据?

时间:2018-10-22 10:55:15

标签: php

假设我有一个教练和球员数据库,像这样的教练表:

  

id
  名称
  图标

玩家表2如下:

  

id
  名称
  年龄
  id_coach

如何从表1中获取每个教练的所有球员,球员的姓名和年龄(表2)以及每个教练的名称和图标?

我有这个sql请求,但它仅显示名称和玩家名称

       SELECT a.name AS coachName, a.icon , b.name , b.age 
        FROM table1 a JOIN
             table2 b
         ON b.id_coach = a.id order by a.id;


                           $output = array();
                            $output2 = '';
                            foreach($this->CoachPlayers as $key => $value){
                                $coachName = $value['coachName'];
                                $coachImage = $value['icon'];
                                $age = $value['age'];
                                if (!array_key_exists($coachName, $output)) {
                                    $output[$coachName] = array();
                                }   
                                $output[$coachName][] = $value['name'];
                                $output[$coachName]['image'] = $value['icon'];
                            }

                            foreach($output as $data => $values) {

                                echo  "<h1>".$data."</h1>";
                                echo '<div style="text-align:center;"><img src="'.URL."public/images/coaches/".$coachImage.'"  /></div>';

                                foreach ($values as $key => $value) {
                                    '<p>'.$value.' </p>';
                                    '<p>'.$age.' </p>';

}

1 个答案:

答案 0 :(得分:0)

尝试下面的代码,它应该可以工作。

    $output = array();
$output2 = '';
foreach($this->CoachPlayers as $key => $value){
    $coachName = $value['coachName'];
    $coachImage = $value['icon'];
    if (!array_key_exists($coachName, $output)) {
        $output[$coachName] = array();
    }
    $player = array();
    $player['name'] = $value['name'];
    $player['age'] = $value['age'];
    $output[$coachName][] = $player;
    $output[$coachName]['image'] = $value['icon'];
}

foreach($output as $data => $values) {
    $coachImage = $values['image'];
    echo  "<h1>".$data."</h1>";
    echo '<div style="text-align:center;"><img src="'.URL."public/images/coaches/".$coachImage.'"/></div>';

    if(is_array($values)) {
        foreach ($values as $key => $player) {
            echo '<p>'.$player['name'].'</p>';
            echo '<p>'.$player['age'].'</p>';
        }
    }
}