从SQL SELECT JOIN(PHP)构建关联数组

时间:2015-04-30 03:12:26

标签: php mysql arrays pdo

我有一个包含用户列表的表。每个用户都有一个包含Select的列。我正在尝试使用与每个用户相关的关联表中的项目列表来填充Select。

我想将这些项目保存到数组中然后在select标记中循环这个数组,但是我失去了每个用户有一个数组并在查询结果中建立关系。我正在使用PDO进行查询。希望你能理解我的问题。我的代码如下,我正在努力做到这一点。我是新手。

经过多次尝试,我得到了这个。

 $stmt = $pdo->prepare("SELECT id,account,gender,age,education,expected_salary,phone,email 
    FROM user 
    ORDER BY id");
    $stmt->execute();
     // set the resulting array to associative
    $seeker_list = $stmt->fetchAll(PDO::FETCH_ASSOC);

    //To get the list for the select <tag>
    foreach($seeker_list as $key => $value){

    $seeker = $value['account'];
    $query = $pdo->prepare('SELECT user_specialty.specialty_id as    id_user_specialty,
                                specialty.specialty
                                FROM user_specialty
                                JOIN specialty ON user_specialty.specialty_id = specialty.id 
                                WHERE user_specialty.user = $seeker');
                                $query->execute();


    $specialty_list = $query->fetchAll(PDO::FETCH_ASSOC) ;    
      foreach($specialty_list as $key => $value){

            echo $value['id_user_specialty'];
    }  
    }

1 个答案:

答案 0 :(得分:1)

它的工作原理如下:

$stmt = $pdo->prepare("SELECT id,account,gender,age,education,expected_salary,phone,email 
FROM user 
ORDER BY id");
$stmt->execute();
 // set the resulting array to associative
$seeker_list = $stmt->fetchAll(PDO::FETCH_ASSOC);

//To get the specialty list
foreach($seeker_list as $key => $value){

$seeker = $value['account'];
$query = $pdo->prepare("SELECT user_specialty.specialty_id, specialty.specialty
                        FROM user_specialty JOIN specialty 
                        ON user_specialty.specialty_id=specialty.id
                        WHERE user_specialty.user=?");
$query->execute(array($seeker));

//To get the specialty list
$specialty_list[$seeker] = $query->fetchAll(PDO::FETCH_ASSOC);
}

并在我打印信息的表格中这样做:

<?php if(!empty($seeker_list)){ 
 foreach ($seeker_list as $key => $value){ ?>
<select>
<?php foreach ($specialty_list[ $value['account']]  as $subkey => $subvalue){ ?>
<option value="<?php  ?>"><?php echo $subvalue['specialty'];  ?></option>