简体   繁体   中英

How to process second dimension of an Array based on similar first dimension value?

I am trying to write some php code to process the second dimension's value of an array based on similar values of the first dimension values.

Following is the sample output.

[0] => Array (
             [0] => 1
             [1] => 0.091238491238491
       )
[1] => Array (
             [0] => 2
             [1] => 0.2221793635487
       )
[2] => Array (
             [0] => 2
             [1] => 0.10662717512033
       )
[3] => Array (
             [0] => 4
             [1] => 0.44354338998346
       )
[4] => Array (
             [0] => 6
             [1] => 0.2248243559719
       )
[5] => Array (
             [0] => 6
             [1] => 0.31764705882353
       )
[6] => Array (
             [0] => 6
             [1] => 0.15764625384879
       )
[7] => Array (
             [0] => 6
             [1] => 0.19160083160083
       )
[8] => Array (
             [0] => 12
             [1] => 0.31054875069499
       )
[9] => Array (
             [0] => 12
             [1] => 0.10915034227918
       )
[10] => Array (
             [0] => 15
             [1] => 0.32915461266474
       )
 //...........goes to 46000 elements

Now what I want to do is, if the index 0 values of each array is similar then I want to add the index 1's value. So for example, if 0 index values for 4 arrays are same , I want to add index 1 values of all 4 arrays. If there is a unique value on 0th index, dont add it with anything, simply store index 1's value and move on.

Thanks very much. Ghanshyam

$added = array();
foreach ($array as $item) {
    if (isset($added[$item[0]])) {
        $added[$item[0]] += $item[1];
    } else {
        $added[$item[0]] = $item[1];
    }
}
$p=0;
$temp =  $final_prod_ex[0][1];
for($x=0; $x<count($final_prod)-1; $x++){
    if($final_prod_ex[$x][0]==$final_prod_ex[$x+1][0]){
        $temp = $temp + $final_prod_ex[$x+1][1];
    }
    else{
        $ans[$p] = $temp."    ".$final_prod_ex[$x][0];
        $temp = $final_prod_ex[$x+1][1];
        $p++;
    }
}

Finally figured it out after a lot of thinking(I'm new to programming)...Array's name is $final_prod_ex. Comment on this if I can make it better. And sorry @deceze. I could not understand your solution. I know you were trying to give the value of one array as an index to another. But what the scenario is, that value isnt like 0,1,2,3,4.... Its like 1,3,5,6,7,10. We are missing numbers in between. Maybe I didnt understand your solution. Correct me if I am wrong. Thanks for all the help.

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