简体   繁体   中英

Generate a multidimensional array with foreach loop

I'am stuck and didn't found any tutorial or examples on how to produce the multidimensional array like this while using foreach() :

'0' => '-- ALL --',
'CATEGORY 1' => array(
    '11'  => 'Item 11',
    '12'  => 'Item 12',
    '13'  => 'Item 13',
),
'CATEGORY 2' => array(
    '14'  => 'Item 14',
    '15'  => 'Item 15',
    '16'  => 'Item 16',
)

And this is where I'am stucked:

$items = $this->model->get_categories();

foreach($items as $item){

    $result[$item->title] = array();

    // HOW TO CONTINUE NEXT ? :(

}

Something like

$items = $this->model->get_categories();

foreach($items as $item){

    $result[$item->title] = array();

    foreach($item->data as $key => $data){ //replace $item->data with whatever your second level stuff is
        $result[$item->title][$key] = $data;
    }

}

Assuming the value is in $item->value:

$result[$item->title][] = $item->value;

will append $item->value to your array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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