Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

foreach loop with counter


Go to End


3 Posts   1603 Views

Avatar
Skullies

Community Member, 19 Posts

31 August 2016 at 7:24pm

Good day
I am trying to get a counter for my foreach loop on my arraylist.
This is what my code looks like at the moment
note : $count = -1; is set like that to start the counter on 0 to work with the arraylist which starts counting at 0

$AmountList = new ArrayList();
		$count = -1 ;
		foreach($Amounts as $item ) {
			$count = $count+1;
			print_r($count);
		//Declare variables and do calculations on them
		$ModelNo = $item['ModelNo'];
		$ImageURL = $item['ImageURL'];
		$Manufacturer = $item['Manufacturer'];
		$Retail = $item['RetailPrice'];
		$IncVat = $item['IncVat'];			
		//Build new array with calculated data
		$AmountList->push(
			new ArrayData(array(
			'ModelNo' => $ModelNo,
			'ImageURL' => $ImageURL,
			'ItemAmount'=>$ItemAmount[$count],
			'Manufacturer' => $Manufacturer,
			'RetailPrice' => ($Retail)*($ItemAmount[$count]),
			'IncVat' => ($Retail)*($AmountItems[$count])*(114)/(100),
			'TotalAmount'=>$IncVat
			))
		);
		return $AmountList;
		}

If anyone can give me any ideas of what i could do better to get the counter to work
Thanks in advance

Avatar
syanaputra

Community Member, 2 Posts

7 September 2016 at 6:16pm

Umm what is not working? If you could provide more information (like why you need those counter, what $ItemAmount and $AmountItems are) maybe we can help better :)

Avatar
blackduck

Community Member, 13 Posts

22 October 2016 at 9:38pm

If you're trying to work from the key for the array and assuming the different arrays share keys, this might be what you're after.
see http://php.net/manual/en/control-structures.foreach.php for using a key with foreach.

$AmountList = new ArrayList();
foreach ($Amounts as $key=>$item) {
	print_r($key);
	//Declare variables and do calculations on them
	$ModelNo = $item['ModelNo'];
	$keymageURL = $item['ImageURL'];
	$Manufacturer = $item['Manufacturer'];
	$Retail = $item['RetailPrice'];
	$keyncVat = $item['IncVat'];			
	//Build new array with calculated data
	$AmountList->push(
		new ArrayData(array(
		'ModelNo' => $ModelNo,
		'ImageURL' => $keymageURL,
		'ItemAmount'=>$itemAmount[$key],
		'Manufacturer' => $Manufacturer,
		'RetailPrice' => ($Retail)*($itemAmount[$key]),
		'IncVat' => ($Retail)*($AmountItems[$key])*(114)/(100),
		'TotalAmount'=>$keyncVat
		))
	);
return $AmountList;
}