简体   繁体   中英

Create new array from a multidimensional if some values are similar in php?

I have an array like below

  Array ( 
    [0] => Array ( [subj_title] => A, [value] => 0 ) 
    [1] => Array ( [subj_title] => B, [value] => 30 ) 
    [2] => Array ( [subj_title] => C, [value] => 6 ) 
    [3] => Array ( [subj_title] => C, [value] => 8 ) 
    [4] => Array ( [subj_title] => C, [value] => 5 ) 
    [5] => Array ( [subj_title] => C, [value] => 11 ) 
  )

I would like this array to be like below

  Array ( 
    [0] => Array ( [subj_title] => A, [value] => 0 ) 
    [1] => Array ( [subj_title] => B, [value] => 30 ) 
    [2] => Array ( [subj_title] => C, [value] => 30 ) //Sum of value C
  )

Trying to find the simplest way to do this, I am kind of messing up with my code. Please refer the work

  $old_subj_title = $subj_title = '';
  $j_subjects = $j_subject = [];  
  foreach($subjects_display as  $r) {
    $subj_title = !empty($r->subj_title) ? $r->subj_title : '';

        if(!empty($subj_title) && $old_subj_title != $subj_title) {
            $j_subject['subj_title'] = $subj_title;
            $j_subject['value'] = $r->marks;
        }
        if($old_subj_title == $subj_title) {
            //something can be done
        } 
        $j_subjects[] = $j_subject;

    $old_subj_title = $subj_title;
  }
  print_r($j_subjects);
  Output:
  Array ( 
    [0] => Array ( [subj_title] => A, [value] => 0 ) 
    [1] => Array ( [subj_title] => B, [value] => 30 ) 
    [2] => Array ( [subj_title] => C, [value] => 6 ) //Single entry of same title
  )

You can try the below code

$data = array ( 
        array ('subj_title' => 'A', 'value' => 0 ) ,
        array ('subj_title' => 'B', 'value' => 30 ) ,
        array ('subj_title' => 'C', 'value' => 6 ) ,
        array ('subj_title' => 'C', 'value' => 8 ) ,
        array ('subj_title' => 'C', 'value' => 5 ), 
        array ('subj_title' => 'C', 'value' => 11 ) 
);
$result = array();
foreach($data as $key => $value){
    $index = $value['subj_title'];
    // Create a new sub array with key as subj_title
    if(!isset($result[$index])){
        $result[$index]['subj_title']   =  $value['subj_title'];
        $result[$index]['value']        =  $value['value'];
    }else{
        // If subarray already exists then values get added
        $result[$index]['value']        =  $result[$index]['value'] + $value['value'];  
    }

}
$result = array_values($result);

echo '<pre>'; 
print_r($result); 

Demo Link

If you are fetching the data using SQL query, You can use GROUP BY to achive the result directly from database as follow

SELECT subj_title, SUM(value) as value FROM yourTable  
       GROUP BY subj_title

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM