从mysql select在objects中创建对象

waxmsbnn  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(255)

我正在使用php和pdo进行这样的基本选择:

SELECT user_id, account, value FROM accounts;

我得到这样的结果:

+---------+---------+-------+
| USER ID | ACCOUNT | VALUE |
+---------+---------+-------+
| 12      | abc     | 12.00 |
| 12      | def     | 98.00 |
| 21      | ghi     | 25.00 |
| 32      | qwe     | 32.00 |
+---------+---------+-------+

我希望它以以下格式保存到数组/对象:

[12] => Array
    (
       [abc] => "12.00"
       [def] => "98.00"
    )
[21] => Array
    (
       [ghi] => "25.00"
    )
[32] => Array
    (
       [qwe] => "32.00"
    )

所以我以后可以这样做:

$myArray['12']['def'] // "98.00"

我想找出最有效的方法来处理这件事。我将有可能有100/1000的用户,每个人将有大约5-10个帐户。
我试过用 fetchAll(PDO::FETCH_GROUP|PDO::FETCH_KEY_PAIR) 但这是不允许的。虽然手册上说它们经常一起使用?
如有任何建议,我们将不胜感激!

i5desfxk

i5desfxk1#

只需使用一个简单的循环来填充适当的数组元素。

$results = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC) {
    $results[$row['user_id']][$row['account']] = $row['value'];
}
qyswt5oh

qyswt5oh2#

将sql代码重新编写为:-

$sql = "select *
        from accounts
        where user_id in (select distinct user_id
                          from accounts)" ;

相关问题