-4

我的 mySQL 数据库中有类似的东西:

sql表

(用户 734 有很多信息:简历、姓名、电话、邮件......)

我想获得一个包含分组数据的数组(在 PHP 中):

array(
    [734]=>
    object {
        [155] => string "Dominique",
        [4] => int(047682037),
        [1] => string "Dominique B"
    },
    [735]=>
    object {
        [155] => string "Other",
        [4] => int(0123456789),
        [1] => string "Other B"
    }
)

不仅适用于 734 用户,而且适用于每个用户。通过一个简单的查询,我得到了所有内容,但顺序不正确。我可以在 SQL 中创建它,还是我可能需要在 PHP 中重新排列数据?

对于每个 user_id,获取所有相关数据的 sql 查询是什么?

我无法更改数据库结构(WP 和 buddypress) 我无法使用原生 WP 功能(因为从另一个站点获取数据)

4

5 回答 5

3
SELECT * FROM (whatever your table name is)
WHERE user_id = (whatever user id you're interested in getting data for)
于 2013-04-24T14:42:46.907 回答
1

解决方案使用ORDER BY

$users = array();
$current_user = null;
$result = $mysqli->query("SELECT user_id, field_id, value FROM `TABLE_NAME` ORDER BY user_id, field_id");
while ($result && $row = $mysqli->fetch_assoc($result)) {
    if ($current_user != $row['user_id']) {
      $current_user = $row['user_id'];
      $users[$row['user_id']] = array();
    }
    $users[$row['user_id']][$row['field_id']] = $row['value'];
}

编辑

还有另一种使用GROUP BYand的解决方案GROUP_CONCAT

$users = array();
$result = $mysqli->query("SELECT user_id, GROUP_CONCAT(field_id SEPARATOR '|') as fields, GROUP_CONCAT(value SEPARATOR '|') as values FROM `TABLE_NAME` GROUP BY user_id");
while ($result && $row = $mysqli->fetch_assoc($result)) {
    $fields = explode('|', $row['fields']);
    $values = explode('|', $row['values']);

    $users[$row['user_id']] = array();
    // Problem id you have your field ids and your values in separate arrays, not sure what you want to do with them
}
于 2013-04-24T15:18:56.293 回答
0
$result = mysqli_query($con, "SELECT * FROM table_name WHERE user_id = 734");

或者,如果您不使用 mysqli:

$result = mysql_query("SELECT * FROM table_name WHERE user_id = 734");
于 2013-04-24T14:47:48.033 回答
0

如果您使用的是 PDO 库,您可以检查 PDO::FETCH_GROUP 属性。 http://php.net/manual/en/pdostatement.fetchall.php

fetch_style: 要返回按指定列的值分组的关联数组,按位或 PDO::FETCH_COLUMN 与 PDO::FETCH_GROUP。

于 2013-04-24T14:53:43.150 回答
0
$stmt = $this->_mysqli->prepare('SELECT user_id,field_id,value FROM WHERE user_id = ?');

$stmt->bind_param('i', $user_id );
$stmt->execute();
$stmt->bind_result($user_id, $field_id, $value);

while($stmt->fetch())
{
     $data[$user_id][$field_id] = $value;
}
于 2013-04-24T14:54:29.517 回答