在php中从mysql查询创建2D数组
我的查询中有以下结果: 我正在尝试在php中创建一个类似这样的数组:在php中从mysql查询创建2D数组,php,mysql,arrays,Php,Mysql,Arrays,我的查询中有以下结果: 我正在尝试在php中创建一个类似这样的数组: [ { "software_version": "1.0", "version_date": "10/08/2016", "changelog": [ { "type": "IMP", "description": "Initial version." }
[
{
"software_version": "1.0",
"version_date": "10/08/2016",
"changelog": [
{
"type": "IMP",
"description": "Initial version."
}
]
},
{
"software_version": "1.0.1",
"version_date": "27/07/2017",
"changelog": [
{
"type": "ADD",
"description": "HostPanel update manager."
},
{
"type": "ADD",
"description": "Hook OnDaemonMinute."
}
]
}
]
我需要将结果与软件版本行相结合。
感谢您的帮助
我的php代码:
$changelog = array();
foreach ($result as $r) {
$changelog[] = array(
'software_version' => $r['software_version'],
'version_date' => $r['version_date'],
'changelog' => array(
array(
'type' => 'IMP', // help
'description' => 'Initial version.'
)
)
);
}
关键是在构建$changelog时将软件版本用作$changelog中的密钥
$changelog = array();
foreach ($result as $r) {
// get the version (just to make the following code more readable)
$v = $r['software_version'];
// create the initial entry for the version if it doesn't exist yet
if (!isset($changelog[$v]) {
$changelog[$v] = ['software_version' => $v, 'version_date' => $r['version_date']];
}
// create an entry for the type/description pair
$change = ['type' => $r['type'], 'description' => $r['description']];
// add it to the changelog for that version
$changelog[$v]['changelog'][] = $change;
}
在对$changelog进行JSON编码之前,您需要使用array_值重新索引$changelog,以便生成您想要的JSON数组输出
$changelog = array_values($changelog);
你为什么要删除你的PHP代码?@Don'tPanic我把它回滚了。谢谢你,你的回答对我帮助很大,我对变量类型做了一个小小的更改。哦,是的,谢谢你抓住了这一点。这就是为什么我们应该尽量避免在没有测试答案的情况下发布答案。