簡體   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