简体   繁体   中英

How can i get sum of the values of an array where array index value starts with same value?

Here are my two arrays.

在此处输入图片说明

This array is $assesment I have tried the code given below and got $cat_array.

    foreach($assesment as $k => $v){
    $k2 = explode("_",$k);
    /* echo "cat : ".$cat = $k2[0] ."-". $v;
    echo "<br>";
    echo "Que : ".$que = $k2[1]."-". $v;
    echo "<br>"; */
    $cat_array[] = $k2[0]."-".$v;   
    }
print_r($cat_array);

在此处输入图片说明

Just update your loop like as

$cat_array = array();
foreach($assesment as $k => $v){
    $k2 = explode("_",$k);
    if(isset($cat_array[$k2[0]])){
        $cat_array[$k2[0]] += $v;
    }else{
        $cat_array[$k2[0]] = $v;
    }
}

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