繁体   English   中英

从数组创建多维数组

[英]Create a multidimensional array from array

我正在尝试将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"
    )
  )
)

我将如何遍历此数组以创建此数组?

数组的维数没有变化,只是进行了重组。 您可以这样做:

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);
<?
$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>';

?>

应该做。 由于您假设我是在紧接插入数据库后不需要将键重置为数字。

这样的事情会工作:

$ 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>';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM