I have this following result in my query:
我的查询中有以下结果:
I'm trying to create an array like this in php:
我正在尝试在php中创建这样的数组:
[
{
"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."
}
]
}
]
I need to combine the result with the software_version
row. Any help is appreciated.
我需要将结果与software_version行结合起来。任何帮助表示赞赏。
My php code:
我的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.'
)
)
);
}
1 个解决方案
#1
1
The key is to use the software version as a key in $changelog
as you build it.
关键是在构建它时将软件版本用作$ 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;
}
You'll need to use array_values
to reindex $changelog
before JSON encoding it in order to produce the JSON array output you're going for.
在JSON编码之前,您需要使用array_values重新索引$ changelog,以便生成您想要的JSON数组输出。
$changelog = array_values($changelog);
#1
1
The key is to use the software version as a key in $changelog
as you build it.
关键是在构建它时将软件版本用作$ 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;
}
You'll need to use array_values
to reindex $changelog
before JSON encoding it in order to produce the JSON array output you're going for.
在JSON编码之前,您需要使用array_values重新索引$ changelog,以便生成您想要的JSON数组输出。
$changelog = array_values($changelog);