Jump to content

Recommended Posts

I would like to access each [price] in [prices] in the following array, to output a list and also show the lowest number.

 

I have tried a foreach loop and the min function but seem to be struggling to access the correct place in the array.

 

Here is the array (as a variable $prices)

Array ( 
	[0] => Array ( 
		[_id] => 20 
		[heading] => All Prices 
		[prices] => Array ( 
			[0] => Array ( 
				[price] => 4.99
			) 
			[1] => Array ( 
				[price] => 9.50 
			) 
			[2] => Array ( 
				[price] => .99 
			)
			[3] => Array ( 
				[price] => 6.75 
			)
			[4] => Array ( 
				[price] => 12.97 
			) 
		) 
	[_page] => /region-tests/index.php 
	[_pageID] => 15 
	[_sortvalue] => 1000
    )
) 
foreach ($prices['price'] as $price) {
  echo "<li>" . $price . "</li>";
}
			  
echo "The lowest price is: " . min($result[0]['prices']);

But my php above is not outputting a list of prices or the lowest price.

 

I get the following errors:

 

For the foreach line:

Notice: Undefined index: price

Warning: Invalid argument supplied for foreach()

 

And the min line:

Notice: Array to string conversion

Look at the structure:

Array ( 
	[0] => Array ( 
		[prices] => Array ( 
$prices is an array (first line) which contains a [0] key (second line) which is itself an array that contains a [prices] key (third line).

 

foreach ($prices[0]["prices"] as $price) {
Each $price looks the same as the first one, which is

			[0] => Array ( 
				[price] => 4.99
			) 
an array that contains a [price] key.

echo "<li>" . $price["price"] . "</li>";

Thanks very much for your reply. 

 

I get the following output with that code.

<b>Notice</b>:  Undefined variable: result in <b>/region-tests/index.php</b> on line <b>49</b><br />
<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/region-tests/index.php</b> on line <b>52</b><br />
<br />
<b>Notice</b>:  Undefined variable: price in <b>/region-tests/index.php</b> on line <b>58</b><br />
<li></li>   
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.