我有一个查询,返回的数据是这样的:
releaseid | name | format |
---------------------------
1 | erbr | CD
1 | erbr | DVD
2 | name | CD
3 | test | CD
4 | yo | CD
4 | yo | CASETE
5 | hey | 8 TRACK
请注意,某些
releaseid
的格式多于1。在PHP中,我使用准备好的语句来初始化数组,如下所示:
$conn = fn_connect(); // my function to connect to db
$q = 'SELECT ....';
$stmt = $conn->prepare($q);
$stmt->bind_param('i', $recordingid);
$stmt->execute();
$stmt->bind_result($id, $name, $format);
$stmt->store_result();
$num_rows = $stmt->num_rows;
if ( $num_rows > 0 ) {
$releases = array();
while ( $stmt->fetch() ) {
$releases[$id] = array('releaseid'=>$id, 'releasename'=>$name, 'releaseformat'=>$format);
}
}
$stmt->free_result();
$stmt->close();
如您所见,当我循环时,我按
releaseid
分组数据,而当releaseid
的格式超过1种时,它仅保留最后一种格式:Array
(
[1] => Array
(
[releaseid] => 1
[releasename] => erbr
[releaseformat] => DVD
)
[2] => Array
(
[releaseid] => 2
[releasename] => name
[releaseformat] => CD
)
...
)
我正在尝试创建一个多维数组,以便我可以保留
releaseid
的所有格式我试过使用以下内容,但同样,它保留了最后一种格式
while ( $stmt->fetch() ) {
$releases[$id] = array('releaseid'=>$id, 'releasename'=>$name, array('format'=>$format));
}
最佳答案
您需要检查$id
中的$releases
条目是否已经存在,如果存在,则将新格式值与其现有的releaseformat
值合并。像这样:
while ( $stmt->fetch() ) {
if (isset($releases[$id])) {
$releases[$id]['releaseformat'][] = $format;
}
else {
$releases[$id] = array('releaseid'=>$id, 'releasename'=>$name, 'releaseformat'=>array($format));
}
}
这将为您提供如下所示的值:
[1] => Array
(
[releaseid] => 1
[releasename] => erbr
[releaseformat] => Array
(
[0] => CD
[1] => DVD
)
)