添加数组元素

时间:2017-06-15 17:05:24

标签: php arrays

我有这个:

Array1 ( [neg] => 0.5 [neu] => 0.25 [pos] => 0.25 ) 

Array2 ( [pos] => 0.5 [neu] => 0.25 [neg] => 0.25 ) 

所以我想在数组1和2中求和。我想对数组1和2中的pos求和,我想对数组1和2中的neu求和,如下所示:

$rating_data = array(

 array('Sentiment', 'rating'),

 array('neg',0.75),

 array('Pos',0.75),

 array('neu',0.50),

);

1 个答案:

答案 0 :(得分:0)

这不是最有效的,但它是可读的。

http://sandbox.onlinephpfunctions.com/code/6cdb4523f6632b1afffd25df34cc2a75e715c4f0

<?php

// Define your output and set them to 0
$negative = 0;
$positive = 0;
$neutral = 0;

// First array
$array1 = array(
    'neg' => 0.5,
    'neu' => 0.25,
    'pos' => 0.25
);

// Loop over each key/value and increment the output variables by that amount  
foreach ($array1 as $key => $value) {
    switch ($key)
    {
       case 'neg':
           $negative += $value;
           break;

        case 'pos':
           $positive += $value;
           break;

        case 'neu':
           $neutral += $value;
           break;
    }
}

// Do exactly the same for array # 2
$array2 = array(
    'pos' => 0.5, 
    'neu' => 0.25, 
    'neg' => 0.25
);

// Same same but different ;)
foreach ($array2 as $key => $value) {
    switch ($key)
    {
       case 'neg':
           $negative += $value;
           break;

        case 'pos':
           $positive += $value;
           break;

        case 'neu':
           $neutral += $value;
           break;
    }
}

// Finally, compose your final array
$rating_data = array(
    array('Sentiment', 'rating'),
    array('neg', $negative),
    array('Pos', $positive),
    array('neu', $neutral),
);

// And output it. 
print_r($rating_data);