SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict Phil-man's Avatar
    Join Date
    Nov 2000
    Posts
    291
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Sum of Specific Values in Multi-Dimensional Array

    Hi. I have an array that consists mostly of other arrays (so I guess it's a multidimensional array). In fact, only the first element in the main array is NOT an array; the rest of the elements are, and they all contain the same type of data. I need to get the sum of, for example, the 2nd value of all of the arrays. How would I do that? Is there some variation of array_sum that lets you get a sum of values across multiple arrays as opposed to getting a sum of the values in a single array? Thanks for any help!

  2. #2
    SitePoint Addict CVPer's Avatar
    Join Date
    Sep 2007
    Location
    Vancouver, BC, Canada
    Posts
    233
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    seems there is no such function you expected.
    but this code may help you
    suppose the multidimensional array like this
    PHP Code:
    $data = array(
        
    1,
        array(
    234),
        array(
    56),
        array(
    78910)
    ); 
    then
    PHP Code:
    function get_second_element(&$data) {
           if (
    is_array($data) && sizeof($data) >= 2) {
               return 
    $data[1];
           }
    }
    echo 
    $sum array_sum(array_map('get_second_element'$data)); 
    output 17
    * @location Vancouver, BC, Canada
    * @name Steve
    * @job PHP/MySQL, Drupal, WordPress Developer

  3. #3
    SitePoint Addict Phil-man's Avatar
    Join Date
    Nov 2000
    Posts
    291
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perfect. Thanks!!


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
  •