Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    May 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Multiplying in an associative multidimensional array

    I have 3 categories: Small box, Medium box, and Large box. Each have the length, width and depth listed. I need to get the volume for each box size. I think I understand how to initialize an associative multidimensional array. I understand how to multiply. I don't understand how to multiply and make a statement for each box's volume. I think it has something to do with a foreach statement but I'm stuck. Please help!!

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Multiplying it can be done with an iteration. IMO, useless in PHP unless you need to recurse it.
    PHP has a function for this called array_product. It works on a single level, but that's not really an issue either.

    PHP Code:
    $aCalcs = array();
    foreach (
    $yourArrayHere AS $key => $value)
    {
        
    $aCalcs[$key] = array_product($value);

    Its not a recursive function, so you'll need to specify which level to work with. It shouldn't care if its associative or not, it will only focus on the (float)$values.

    For a more advanced feature, you could use a class for this as well:
    PHP Code:
    class Box
    {
        private 
    $sBoxName;
        private 
    $x;
        private 
    $y;
        private 
    $z;
        public function 
    __construct($sBoxName$x$y$z)
        {
            
    $this->sBoxName $sBoxName;
            
    $this->$x;
            
    $this->$y;
            
    $this->$z;
        }
        
    // You'd have getters/setters to access / mutate the data here, but I won't add those
        
    public function getVolume()
        {
            return 
    $this->$this->$this->z;
        }
    }

    // Used
    $aBoxes = array(
        new 
    Box('Small Box'111),
        new 
    Box('Medium Box'222),
        new 
    Box('Large Box'333)
    );

    foreach (
    $aBoxes AS $box)
    {
        
    // getName would be one of the accessors which I skipped
        
    print $box->getName() . ' has ' $box->getVolume() . ' volume available';



  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •