我有一个阵列。我发布的是JSON,因为这是我的API输出。
[
{
"compId": 26,
"addonId": "1",
"addonRate": "32"
},
{
"compId": 26,
"addonId": "2",
"addonRate": "51"
},
{
"compId": 7,
"addonId": "1",
"addonRate": "11"
},
{
"compId": 7,
"addonId": "2",
"addonRate": "12"
}
]
我想转换那个数组,以便我可以获得以下输出:
[
{
"addonId": "1",
"companies": {
"compId": 26,
"addonRate": "32"
},
{
"compId": 7,
"addonRate": "11"
}
},
{
"addonId": "2",
"companies": {
"compId": 26,
"addonRate": "51"
},
{
"compId": 7,
"addonRate": "12"
}
}
]
到目前为止,我能够提取不同的compId
和addonId
。但后来我想在每个插件中添加这些公司以及子阵列中相应的速率。
任何帮助都会很棒! 感谢
答案 0 :(得分:1)
你有没有试过像
这样的东西$newArray = array();
foreach ($startingArray as $row) {
if (!isset($newArray[$row['addonId']])
$newArray[$row['addonId']] = array(
'addonId'=>$row['addonId'],
'companies'=>array()
);
}
$newArray[$row['addonId']]['companies'][] = array(
"compId"=> $row['compId'],
"addonRate"=> $row['addonRate']
);
}