simonclay Posted March 24, 2017 Share Posted March 24, 2017 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 Quote Link to comment Share on other sites More sharing options...
requinix Posted March 24, 2017 Share Posted March 24, 2017 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>"; Quote Link to comment Share on other sites More sharing options...
simonclay Posted March 24, 2017 Author Share Posted March 24, 2017 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> Quote Link to comment Share on other sites More sharing options...
requinix Posted March 24, 2017 Share Posted March 24, 2017 That would have to do with code that you haven't posted. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.