我有一张包含用户列表的表格。每个用户都有一个带有 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'];
}
}
最佳答案
它是这样工作的:
$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);
}
然后在我正在打印信息的 table 上这样做:
<?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>
关于php - 从 SQL SELECT JOIN (PHP) 构建关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29958372/