Jump to content

Associative array/multidimensional....help please


chito

Recommended Posts

Hello, Im just learning and getting started with PHP and I've searched high and low for the answer myself and can't seem to find the right application. My assignment requires pulling the price and shipping cost out of this and sending it to a function that does the calculation for each item. The way I have it below works, but my instructor wants me to have the array be more descriptive as in example 2. For some reason I can't figure out how to manipulate the loop to get the extracted items to the variables as I need them, any advice?

Thanks for any clarity you can offer..

 

example 1: It works as I need it to.

<B>Checkout</B><br>

Below is a summary of the products you wish to purchase, along with totals:

<?php

 

# Enclosed the calculations into a function

function subtotals($price,$shipping,$tax) {

$total_price += $price;

$total_tax += $tax * $price;

$total_shipping += $shipping * $price;

$grand_total += ($total_price + $total_tax + $total_shipping);

return $grand_total;

}

 

$products = array ("Candle Holder" => array ("12.95", "0"),

"Coffee Table" => array ("99.50", "0.10"),

"Lamp" => array ("42.99", "0.10")

);

 

 

#tax rate is constant

$tax = 0.08;

$total_price = 0;

$total_tax = 0;

$total_shipping = 0;

$grand_total = 0;

?><ul><?

 

# Foreach loop grabs value from each item and populates variable for calc and echo's subtotal

foreach ($products as $key =>$value) {

list($price,$shipping)=$value;

$subtotals += subtotals($price, $shipping, $tax);

echo "<li>".$key.": $".$price;

}

 

?>

 

</ul>

<hr>

<br>

<B>Total (including tax and shipping): $<? echo $subtotals; ?></B>

 

 

Example 2: Teacher requests I set up array as so:

 

$products = array (array ("item"=>"Candle Holder","price"=>"12.95","shipping"=> "0"),

                            array ("item"=>"Coffee Table","price"=>"99.50","shipping"=> "0.10"),

                            array ("item"=>"Lamp","price"=>"42.99","shipping"=> "0.10")

);

Link to comment
Share on other sites

Hello.

 

Please use php /php tags bbcode tags around your code.  Makes it a lot easier for people to read. 

 

[code=php:0] Your code [/[code=php:0]

 

So to answer your question, based on your teacher's array:

 


foreach ($products as $product) {
  $subtotals += subtotals($product['price'], $product['shipping'], $tax);
  echo "</pre>
<li>{$product['item']}: {$product['price']}</li>";<br

 

 

Link to comment
Share on other sites

Ok my teacher came back telling me that the array i used with the above response that solved my issue was not to her liking.

 

$products = array (array ("item"=>"Candle Holder","price"=>"12.95","shipping"=> "0"),

                            array ("item"=>"Coffee Table","price"=>"99.50","shipping"=> "0.10"),

                            array ("item"=>"Lamp","price"=>"42.99","shipping"=> "0.10")

 

She stated that it was better to format in this way, but without and explanation why..

 

$products = array ("Candle Holder"=>array("price"=>"12.95","shipping"=> "0"),

                              "Coffee Table"=>array("price"=>"99.50","shipping"=> "0.10"),

                                          "Lamp"=>array("price"=>"42.99","shipping"=> "0.10")

);

 

From all the examples I've seen in most books and online sources I've seen the first example used, any reason why the 2nd would be a better or worse option?

 

Thanks.

 

Link to comment
Share on other sites

I'd say it's just a matter of opinion. There's not even that much of a difference in how you'd retrieve the information if the array changed over time...

 

First Array:

<?php
foreach($products as $product) {
echo "Item : " . $product['item'] . "<br />"
       ."Price : " . $product['price'] . "<br />"
       ."Shipping : " . $product['shipping'];
}
?>

 

Second Array:

<?php
foreach($products as $item=>product) {
echo "Item : " . $item . "<br />"
	."Price : " . $product['price'] . "<br />"
	."Shipping : " . $product['shipping'];
}
?>

 

Looking above, I think I'd more likely use the first array that you posted, just because the code for the foreach looks better and more uniform to me.

 

Link to comment
Share on other sites

Just a matter of array lookups

using your array structure, in order to find the 'Lamp', you would have to iterate thru each item in your array, until you find the item.

the second is a bit more convienent, when doing lookups for the item

 

but when dealing with databases, its faster to use INTEGERS as primary keys, and integers are more easily validated/processed in web apps.

so it really depends on the usage of your array, if you want to use a named index key system or an integer index key system.

The named index key system also helps when debugging code as well as others to read your code without a lot of stuggle

 

I use both systems depending on their usage in my apps,

 

So I think, she means by readabilty. its easier to understand this in your app

$price = $item['lamp']['price] + ($item['lamp']['price']*$tax) + $item['lamp']['shipping']

than it is this

$price = $item[2][1] + ($item[2][1]*$tax) + $item[2][2];

Link to comment
Share on other sites

Thanks all, I guess there are many ways to do the same thing, the way I had it just made sense to me, but I see the other points as well. Made an adjustment to the foreach loop to endup looking like this, I do think the first way looked more efficient tho.

 

foreach ($products as $product=>$value) {

  foreach ($value as $item=>$x);

  $subtotals += subtotals($value['price'], $value['shipping'], $tax);

  echo "<li>$product: {$value['price']}</li>";

  }

 

This is a great site for someone like me just learning and grow my knowledge..thanks again.

 

Link to comment
Share on other sites

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.