从PHP中的循环创建关联的多维数组
作者:互联网
如何使用循环从数据库结果集中在PHP中创建如下数组:
Array
(
[T] => Array
(
[0] => Array
(
[id] => 1
[name] => Timer
)
[1] => Array
(
[id] => 2
[name] => Tub
)
)
[P] => Array
(
[0] => Array
(
[id] => 3
[name] => Paper
)
[1] => Array
(
[id] => 4
[name] => Puppy
)
)
)
您会注意到,数组键是一个字母,该字母取自结果集中的“名称”值.循环将是这样的:
while($result = $db->fetch($query) {
$key = $result['name']{0};
// your answer :-)
}
解决方法:
我认为应该这样做:
$sql = 'SELECT id, name FROM table';
$result = mysql_query( $sql);
$answer = array();
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = $row;
}
mysql_free_result( $result);
var_dump( $answer);
或者,更具体地说(如果您的查询返回的列不仅仅是ID和名称):
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
标签:associative,multidimensional-array,arrays,php 来源: https://codeday.me/bug/20191101/1987351.html