简体   繁体   中英

Php array dynamic fill

how can i fill following type array dynamicly in for loop

   array('items'=>array(
array('label'=>'News', 'url'=>array('/site/index')),
array('label'=>'News2', 'url'=>array('/site/2')),
));

I am new in programming

thanks for help

Try this:

$arr = array();

for($i = 1; $i <= $count; $i++) {
    $arr[] = array(
        'label' => 'News'.($i > 1 ? $i : ''),
        'url' => $i == 1 ? '/site/index' : '/site/'.$i
    )
}

$result = array('items' => $arr);

And the resulting array will be in the form:

array('items' => array(
    array(
        'label' => 'News',
        'url' => '/site/index'
    ),
    array(
        'label' => 'News2',
        'url' => '/site/2'
    ),
    array(
        'label' => 'News3',
        'url' => '/site/3'
    ),
    array(
        'label' => 'News4',
        'url' => '/site/4'
    )
));

..depending on the $count variable.


for($i = 0; $i < $items; $i++) { //where $items is number of news items
    if($i == 0)
        $value = "Index";
    else
        $value = $i+1;
    $ar["items"]["News".$i] = $value;
}

You can access the array by square brackets, by both alphanumerical and purely numerical keys. Anyway I suggest reading a basic php course.

use for to loop like :

$items=array();
for($i=1;$i<=$max_count;$i++){
$element = array('label'=>'news'.$i,'url'=>'/site/index'.$i);
$items[] = $element;
}

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