我尝试通过php从我的mysql数据库中获取数据。我想使用json,因为在我们的Android应用程序中处理它非常好。
我尝试以下方法: 我们有三个数据表:
User:
-id
-name
REF_Interests
-ref_interests_id
-interestName
User_Ref_Interests
-id
-userid
-ref_interests_id
我们创造了几个用户和兴趣,例如"游泳"使用ref_interests_id = 1(例如)
对于每个拥有类似兴趣的数组的用户,如何只能获得一行:
User:
-id
-name
-interests:
--interest
---ref_interest_id
---interestName
--interest
---ref_interest_id
---interestName
--...
---...
---...
如果此用户有4个兴趣点,我会加入为一个用户返回4行的表。我觉得处理起来非常不舒服。那么有比实际解决方案更好的方法吗?
非常感谢你!
答案 0 :(得分:1)
不幸的是,你无法在一个MySQL查询中执行此操作。
我可以建议2个解决方案:
我希望它会有所帮助。
编辑2:
前两种查询方式。它只从DB获得所需的数据:
<?
$pdo = new PDO('mysql:host=localhost;dbname=tesst', 'root', '');
// add your conditions into WHERE section
$stmt = $pdo->prepare('SELECT * FROM User WHERE 1=1');
$stmt->execute();
$rawUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);
$userIds = array();
$users = array();
foreach ($rawUsers as $user) {
$userIds[] = (int)$user['id'];
$users[$user['id']] = $user;
$users[$user['id']]['interests'] = array();
}
$stmt = $pdo->prepare('
SELECT *
FROM User_Ref_Interests
JOIN REF_Interests
ON REF_Interests.ref_interests_id = User_Ref_Interests.ref_interests_id
WHERE User_Ref_Interests.userid IN ('.implode(',', $userIds).')
');
$stmt->execute();
$interests = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($interests as $interest) {
$users[$interest['userid']]['interests'][] = array('ref_interest_id' => $interest['ref_interests_id'], 'interestName' => $interest['interestName']);
}
echo '<pre>';
echo json_encode($users, JSON_PRETTY_PRINT);
echo '</pre>';
输出将是:
{
"1": {
"id": "1",
"name": "u1",
"interests": [
{
"ref_interest_id": "1",
"interestName": "i1"
},
{
"ref_interest_id": "2",
"interestName": "u2"
},
{
"ref_interest_id": "3",
"interestName": "i3"
}
]
},
"2": {
"id": "4",
"name": "u4",
"interests": []
}
}
答案 1 :(得分:0)
我将代码更改为我的需求,但是当我在谷歌浏览器中调用它时,它没有显示任何错误。
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//
// NOTE: this code for PHP 5.4 and greater (because i use new array syntax)
//
echo "0";
$pdo = new PDO('mysql:host=servername;dbname=dbname', 'name', 'pw');
echo "1";
// add your conditions into WHERE section
$stmt = $pdo->prepare('SELECT * FROM user WHERE 1=1');
$stmt->execute();
$rawUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "2";
$userIds = [];
$users = [];
foreach ($rawUsers as $user) {
$userIds[] = (int)$user['id'];
$users[$user['id']] = $user;
$users[$user['id']]['interests'] = [];
}
echo "3";
$stmt = $pdo->prepare('
SELECT *
FROM zuordnunguserinteressen
JOIN interessen
ON interessen.id = zuordnunguserinteressen.InteressenID
WHERE zuordnunguserinteressen.UserID IN ('.implode(',', $userIds).')
');
echo "4";
$stmt->execute();
$interests = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "2";
foreach ($interests as $interest) {
$users[$interest['userid']]['interests'][] = ['InteressenID' => $interest['InteressenID'], 'Interesse' => $interest['Interesse']];
}
echo '<pre>';
echo json_encode($users, JSON_PRETTY_PRINT);
echo '</pre>';
?>