I am currently going to school for Web Design, and I am now in a PHP class, but I am having a problem understanding how to loop through an array while looking at a specific value, storing the values that are greater than the value in the first array, and ultimately displaying the name of the array that has the lowest value of them all. Here’s what I have done so far and where I’m not sure how to proceed:
[php]
// These are the arrays I’m working with.
$beverages = array(
array(
‘product’ => ‘Dr. Pepper’,
‘calories’ => ‘150’,
‘fat’ => ‘0’,
‘carbs’ => ‘40g’,
‘sodium’ => ‘55mg’,
‘sugar’ => ‘40g’
),
array(
‘product’ => ‘Coca-cola’,
‘calories’ => ‘140’,
‘fat’ => ‘0’,
‘carbs’ => ‘39g’,
‘sodium’ => ‘45mg’,
‘sugar’ => ‘39g’
),
array(
‘product’ => ‘Pepsi’,
‘calories’ => ‘150’,
‘fat’ => ‘0’,
‘carbs’ => ‘41g’,
‘sodium’ => ‘30mg’,
‘sugar’ => ‘41g’
),
array(
‘product’ => ‘Sprite’,
‘calories’ => ‘90’,
‘fat’ => ‘0’,
‘carbs’ => ‘24g’,
‘sodium’ => ‘40mg’,
‘sugar’ => ‘24g’
)
);
// The next thing I had to do was remove the ‘fat’ item from each array before I start the loop.
foreach($beverages as $key => $beverage) {
if($beverage[‘fat’] == 0){
unset($beverages[$key][‘fat’]);
}
}
echo ‘
’;’;
print_r($beverages);
echo ‘
// The next thing I needed to do was to create a variable to store the value of ‘calories’ for the first array., and create a variable for ‘product’.
$calories = ‘calories’;
$name = ‘product’;
// Now this is where I’m unsure. I now need to loop through each array to see if the calories in the first array is lower than the calories in the current item that is being looped through. If the calories are lower, I need to store the amount of $calories for that product. Then store the name of the product in $name.
foreach ($beverages as $key => $calories) {
if ($value > $calories)
}
// After all that is done, I need to echo the product $name that has the lowest calories in the arrays.
echo ‘The lowest calorie product is ’ . $name . ’ with ’ . $calories . ’ calories.’;
[/php]
Everywhere I turned online, I kept seeing very specific examples, specifically pertaining to numbers and a single array, not arrays within an array, so hopefully someone here can help me figure out what I’m doing wrong, and if you can, please explain what I’ve done wrong so that I can understand it.