Search code examples
phparraysobjectassociative

How can I filter data from my array php?


I am really struggling filtering my data.I know how to access parts of the array but am struggling on how to filter. I know how to do it in SQL SUM & count) but not when it comes to PHP arrays please help.

I need to filter some of my data stored in the variable $res.

I need to see how many times each 'REF' appears & total 'LCL_D_CBM' for each ref all of this where the "TERR" is equal to "TERR1".

foreach ($res as $res1){


   if ($res1["TERR"] == "TERR1"){

   //the individual ref 
   //$res1['REF'];  


   // the coutn of how many times each ref appears
   //echo count($res1['REF']);

   //sum
   //echo array_sum($res1['LCL_D_CBM']);    



   }
}

need result to be like -

CEA

3

2561

CEF

456

135

var_dump($res); gives me below

array(350) { 
  
[0]=> array(7) { [0]=> string(3) "CEA" ["REF"]=> string(3) "CEA" [1]=> string(5) "1.080" ["LCL_D_CBM"]=> string(5) "1.080" [2]=> string(3) "WF2" ["AREA_CODE"]=> string(3) "WF2" ["TERR"]=> string(5) "TERR1" } 
            
[1]=> array(7) { [0]=> string(3) "CEA" ["REF"]=> string(3) "CEA" [1]=> string(5) "2.000" ["LCL_D_CBM"]=> string(5) "2.000" [2]=> string(4) "HU13" ["AREA_CODE"]=> string(4) "HU13" ["TERR"]=> string(5) "TERR1" } 
            
[2]=> array(7) { [0]=> string(3) "CEF" ["REF"]=> string(3) "CEA" [1]=> string(5) "2.448" ["LCL_D_CBM"]=> string(5) "2.448" [2]=> string(4) "TW16" ["AREA_CODE"]=> string(4) "TW16" ["TERR"]=> string(5) "TERR2" } ..... etc


Solution

  • You can solve it like this. Not a pretty solution, but should do the work. (I did not test this, so it might contain a spelling error or something):

    $sum_lcl = 0;
    $unique_refs = array();
    foreach ($res as $res1){
    
        if (!array_key_exists($res1['REF'], $unique_refs)) {
            $unique_refs[$res1['REF']] = array();
        }   
    
        $unique_refs[$res1['REF']]['SUM'] = ( array_key_exists('SUM', $unique_refs[$res1['REF']]) ) ? ( intval( $unique_refs[$res1['REF']]['SUM'] ) + 1 ) : 1;
        $unique_refs[$res1['REF']]['LCL_SUM'] = ( array_key_exists('LCL_SUM', $unique_refs[$res1['REF']]) ) ? ( floatval( $unique_refs[$res1['REF']]['LCL_SUM'] ) + floatval( $res1['LCL_D_CBM'] ) ) : 1;
    
    
    }
    
    
    foreach( $unique_refs AS $unique => $data ){
        $title = $unique;
        $sum = $data['SUM'];
        $lcl_sum = $data['LCL_SUM'];
        echo "{$title}<br />{$sum}<br />{$lcl_sum}";
    }