SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict TegSkywalker's Avatar
    Join Date
    Nov 2001
    Location
    USA
    Posts
    214
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Multiply matching keys in two arrays

    Oh ok. I do have a question though: Say I have two arrays where the first array contains the number of "tutoring sessions" and the second array contains the "lesson duration":

    PHP Code:
    Array ([0] => 2  [1] => 
    Array ([
    0] => 45  [1] => 90 
    and what I want to do is multiply the matching keys between the two. For example, key of [0] is in both arrays and i want to multiply 2 * 45 and 3 * 90.

    In addition do that I want to take those results and add them together to get total minutes (in this example, it is 90 + 270 = 360). From there I would take the result and say like "Total lesson minutes: 360"

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,033
    Mentioned
    152 Post(s)
    Tagged
    2 Thread(s)
    PHP Code:
    $sessions = array(23);
    $duration = array(4590);
    $total 0;
    foreach(
    $sessions as $i => $num) {
      if (isset(
    $duration[$i]))
        
    $total += $num $duration[$i];
    }
    echo 
    'Total lesson minutes: '$total
    Rémon - Hosting Advisor

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  3. #3
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    <?php
    function multiply($a$b){
      return 
    $a $b;
    }

    function 
    stuff($arrayOne$arrayTwo){
      
    $computed = array();
      for(
    $index 0$index count($arrayOne); $index++){
        
    array_push($computedmultiply($arrayOne[$index], $arrayTwo[$index]));
      }
      return 
    array_sum($computed);
    }

    echo 
    stuff(
      array(
    1005),
      array(
    510)
    ); 
    #550

    ?>
    Off Topic:

    Dammit ScallioXTX!
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  4. #4
    SitePoint Addict TegSkywalker's Avatar
    Join Date
    Nov 2001
    Location
    USA
    Posts
    214
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks ScallioXTX! Your solution helped me out and now I know something to use in the future that I was stumped with before. This forum never disappoints with the quick and concise help.


Bookmarks

Posting Permissions

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