2

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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;
}

1 Comment

what you want in your entries ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.