我正在尝试将关联数组从Drupal数据库转换为可以编码为json的多维数组。
我从:
开始$notifications =`
Array
(
[0] => Array
(
[rfp_id] => RFP-013-2014(C)
[notification_type] => due_date
)
[1] => Array
(
[rfp_id] => RFP-013-2014(C)
[notification_type] => changes
)
[2] => Array
(
[rfp_id] => RFP-013-2014(C)
[notification_type] => due_date
)
[3] => Array
(
[rfp_id] => RFP-014-2014(C)
[notification_type] => due_date
)
[4] => Array
(
[rfp_id] => RFP-014-2014(C)
[notification_type] => changes
)
)
我想通过rfp_id字段进行分组,最后得到类似的结果:
Array (
[0]=> Array (
["rfp_id"]=>"RFP-014-2014"
["notification_type"]=>
Array (
[0]=> "date_due"
[1]=> "changes"
)
)
)
如何循环使用此数组来创建它?
答案 0 :(得分:1)
阵列的维度没有变化,只是重组了。你可以这样做:
foreach ($notifications as $notification)
{
$rfp_id = $notification['rfp_id'];
$newArray[$rfp_id]['rfp_id'] = $rfp_id;
$newArray[$rfp_id]['notification_type'][] = $notification['notification_type'];
}
echo '<pre>'.print_r($newArray,TRUE).'</pre>';
正如您所看到的,我已经完成了与指定的略有不同,只是因为它更容易。如果你想要数字键,你可以这样做:
$newArray = array_values($newArray);
答案 1 :(得分:1)
<?
$result = array();
foreach ($notifications as $key => $note) {
$result[$note['rfp_id']]['rfp_id'] = $note['rfp_id'];
$result[$note['rfp_id']]['notification_type'][] = $note['notification_type'];
}
echo '<pre>';
print_r($result);
echo '</pre>';
?>
应该这样做。由于您在我假设您不需要将密钥重置为数字后立即插入数据库。
答案 2 :(得分:0)
这样的事情会起作用:
$ array = array();
//loop over the array
foreach($notifications as $row){
//if this rfp id doesn't exist, add it
if(!isset($array[$row['rfp_id']])){
//add the first entry in the array
$array[$row['rfp_id']] = array(
'rfp_id'=>$row['rfp_id'],
'notification_type'=>array(
$row['notification_type']
)
);
} else {
//rfp_id exists, so just append the notification type
$array[$row['rfp_id']]['notification_type'][] = $row['notification_type'];
}
}
//get just the values to reset the first level keys to numeric.
$array = array_values($array);
//display the array
echo '<pre>'.print_r($array,true).'</pre>';