4

如何使用循环从数据库结果集中在 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  :-)

}
4

3 回答 3

6

我认为应该这样做:

$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);

或者,更具体地说(如果您的查询返回的列不仅仅是idand name):

while( $row = mysql_fetch_assoc( $result))
{
    $answer[ strtoupper($row['name'][0]) ][] = array(
        'id' => $row['id'],
        'name' => $row['name']
    );
}
于 2011-12-08T20:40:59.893 回答
0
$indexArray = array(); // Array from Example
while($result = $db->fetch($query) {
    $key = $result['name']{0};
    if(!isset($indexArray[$key])) {
        $indexArray[$key] = array();
    }
    array_push($indexArray[$key], $result);
}
于 2011-12-08T20:43:54.330 回答
0
$results = array();
while($result = $db->fetch($query)) {
  $key = strtoupper($result['name'][0]);
  if(!isset($results[$key]))
    $results[$key] = array();
  $results[$key][] = $result;
}
于 2011-12-08T20:48:07.950 回答