Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>function extractData( array $data, $store = null ) { $callback = function( $values, $array ) use ( $store ) { // We require values for a particular store if( ! is_null( $store ) ) { if( $array[ 'store' ] == $store ) { return $array; } return false; } // Return the sum of all stores in a city else { // Toss out the city and store values since they're not needed unset( $array['city'], $array['store'] ); // Seed the initial values if( ! is_array( $values ) || empty( $values ) ) { return $array; } // array_map function used add the arrays $add = function( $a, $b ) { return $a + $b; }; // Add the arrays $summedArray = array_map( $add, $values, $array ); // Return the combined array structure return array_combine( array_keys( $values ), $summedArray ); } }; return array_reduce( $data, $callback, array() ); } $data = array( 0 =&gt; array( "city" =&gt; 309, "store" =&gt; 12, "apples" =&gt; 21, "oranges" =&gt; 14, "lichis" =&gt; 34 ), 1 =&gt; array( "city" =&gt; 309, "store" =&gt; 13, "apples" =&gt; 0, "oranges" =&gt; 11, "lichis" =&gt; 32 ), 2 =&gt; array( "city" =&gt; 309, "store" =&gt; 14, "apples" =&gt; 44, "oranges" =&gt; 61, "lichis" =&gt; 0 ), 3 =&gt; array( "city" =&gt; 309, "store" =&gt; 15, "apples" =&gt; 7, "oranges" =&gt; 0, "lichis" =&gt; 6 ), 4 =&gt; array( "city" =&gt; 309, "store" =&gt; 16, "apples" =&gt; 0, "oranges" =&gt; 0, "lichis" =&gt; 12 ) ); // Return the values for a particular store print_r( extractData( $data, 16 ) ); // Return the total of all stores in the city print_r( extractData( $data ) ); </code></pre> <p>Which would yield the following results...</p> <p><strong>Single City</strong></p> <pre><code>Array ( [city] =&gt; 309 [store] =&gt; 16 [apples] =&gt; 0 [oranges] =&gt; 0 [lichis] =&gt; 12 ) </code></pre> <p><strong>Totals</strong></p> <pre><code>Array ( [apples] =&gt; 72 [oranges] =&gt; 86 [lichis] =&gt; 84 ) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload