Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从MySQL选择在对象中创建对象_Php_Mysql_Arrays_Pdo - Fatal编程技术网

Php 从MySQL选择在对象中创建对象

Php 从MySQL选择在对象中创建对象,php,mysql,arrays,pdo,Php,Mysql,Arrays,Pdo,我正在使用PHP和PDO进行这样的基本选择: SELECT user_id, account, value FROM accounts; 我得到这样的东西: +---------+---------+-------+ | USER ID | ACCOUNT | VALUE | +---------+---------+-------+ | 12 | abc | 12.00 | | 12 | def | 98.00 | | 21 | ghi

我正在使用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 |
+---------+---------+-------+
$myArray['12']['def'] // "98.00"
我希望它以以下格式保存到数组/对象:

[12] => Array
    (
       [abc] => "12.00"
       [def] => "98.00"
    )
[21] => Array
    (
       [ghi] => "25.00"
    )
[32] => Array
    (
       [qwe] => "32.00"
    )
这样我以后可以做这样的事情:

+---------+---------+-------+
| USER ID | ACCOUNT | VALUE |
+---------+---------+-------+
| 12      | abc     | 12.00 |
| 12      | def     | 98.00 |
| 21      | ghi     | 25.00 |
| 32      | qwe     | 32.00 |
+---------+---------+-------+
$myArray['12']['def'] // "98.00"
我想找出最有效的方法来处理这件事。我将有可能拥有100/1000的用户,每个用户将拥有大约5-10个帐户

我尝试使用fetchAllPDO::FETCH_组| PDO::FETCH_密钥对,但这是不允许的。尽管手册上说它们经常一起使用


任何建议都将不胜感激

将SQL代码重新编写为:-

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

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

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

. 我会使用它,然后在您想要的设置中构建一个新数组。我想您需要PDO::FETCH|COLUMN | PDO::FETCH_GROUP@AbraCadaver-这并没有提供期望的结果。@漂白剂-我希望有一个与PDO更相关的解决方案。链接问题中的答案引用了PDO::FETCH_ASSOC。这就是我在这里要使用的。然后使用该数组来构建新数组。WHERE子句没有任何区别。一行怎么可能不符合该条件?我很确定它符合。再次检查它。这确实符合我的需要。我想得太多了,把事情弄得比需要的复杂得多。谢谢你,巴尔马!