Reputation: 145
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
Upvotes: 2
Views: 11876
Reputation: 124768
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.
Upvotes: 4
Reputation: 125496
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;
}
Upvotes: 0
Reputation: 2417
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.
Upvotes: 2