2017-06-15 228 views
0

我有這樣的:添加數組元素的

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

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

所以我想求和NEG陣列中1和2。我想求和POS陣列1和2中,我想求和在陣列1和2中的neu是這樣的:

$rating_data = array(

array('Sentiment', 'rating'), 

array('neg',0.75), 

array('Pos',0.75), 

array('neu',0.50), 

); 
+0

大,讓我們知道這一切是如何變成了。或者你總是可以問一個問題。或者向我們展示一些您嘗試過的代碼 – RiggsFolly

回答

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);