Php array: add values of key 'x' for the Same Values of key 'y'

How can I add values of key 2 of inner arrays for the similar values of key 0 of inner arrays.

Thanks for your help i’m stuck on this problem. Let me explain it, i have this kind of array.

  array (size=6)
  0 => 
    array (size=4)
      0 => float 10002
      1 => string 'xxxyyyy' (length=7)
      2 => float 5.00
      3 => float 0
  1 => 
    array (size=4)
      0 => float 10002
      1 => string 'xxxyyyy' (length=7)
      2 => float 5.00
      3 => float 4.25
  2 => 
    array (size=4)
      0 => float 10002
      1 => string 'xxxyyyy' (length=7)
      2 => float 5.00
      3 => float 0
  3 => 
    array (size=4)
      0 => float 10010
      1 => string 'yyyyyyy' (length=7)
      2 => float 10.00
      3 => float 0
  4 => 
    array (size=4)
      0 => float 10010
      1 => string 'yyyyyyy' (length=7)
      2 => float 10.00
      3 => float 1.85
  5 => 
    array (size=4)
      0 => float 10010
      1 => string 'yyyyyyy' (length=7)
      2 => float 10.00
      3 => float 0

Is it possible to get this result? (if key0 values are same of inner arrays then sum key2 values )

sum_key_2 = 15, for key_0 = 10002
sum_key_2 = 30, for key_0 = 10010

I tried this but not getting desired output:

$bill = 0; $sp_no = array();
foreach($data as $innerKey => $innerArray) {
  $sp_no[] = $innerArray[0];
}

foreach($data as $k => $val) {
  if ($sp_no[$k] == $val[0]) {
    $bill += $val[2];
  }
}
echo $bill;

Hi @rakeshramteke8007 and welcome to the forums.

Try this:

<?php 
  declare(strict_types=1); // REMOVE IF NOT PHP7
  ini_set('display_errors', '1');
  error_reporting(-1); // E_ALL|E_STRICT);

$data = [
  0 =>  [10002,  'xxxyyyy',  5.00, 0],
  1 =>  [10002,  'xxxyyyy',  5.0, 4.25],
  2 =>  [10002,  'xxxyyyy',  5.00, 0],
  3 =>  [10010,  'yyyyyyy', 10.00, 0],
  4 =>  [10010,  'yyyyyyy', 10.00, 1.85],
  5 =>  [10010,  'yyyyyyy', 10.00, 0],
]; 
fred ($data);      

$bill_A  = 0; 
$bill_B  = 0;
# $sp_no   = array();
foreach($data as $innerKey => $innerArray)
{
  if( 10002 === $innerArray[0]):
    $bill_A += $innerArray[2];
    # fred($bill_);
  endif;  

  if( 10010 === $innerArray[0]):
    $bill_B += $innerArray[2];
  endif;  
}

echo '<br>$bill_A ==> ' .$bill_A;
echo '<br>$bill_B ==> ' .$bill_B;

//=================
function fred($val)
{
  echo '<pre style="width:88%; margin:1em auto; background-color:#9ff;">'; 
  if(1):
      var_dump($val); 
  else:    
    print_r($val);
  endif;  
  echo '<br></pre>';
}

Output:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.