2017-09-07 98 views
0

我有2个阵列在PHP语言:PHP合并2个阵列基于相同的特定键

Array 
(
    [0] => Array 
     (
      [amount] => 21600.00 
      [rows] => 2 
      [student_id] => 1 
     ) 

) 

Array 
(
    [0] => Array 
     (
      [amount] => 541990.00 
      [rows] => 512 
      [student_id] => 1 
     ) 

    [1] => Array 
     (
      [amount] => 347480.00 
      [rows] => 281 
      [student_id] => 2 
     ) 

    [2] => Array 
     (
      [amount] => 507400.00 
      [rows] => 214 
      [student_id] => 3 
     ) 
) 

我想基于相同student_id数据值合并这两个数组,所以我希望得到的结果会是这样:

Array 
(
    [0] => Array 
     (
      [amount] => 563590.00 
      [rows] => 514 
      [student_id] => 1 
     ) 

    [1] => Array 
     (
      [amount] => 347480.00 
      [rows] => 281 
      [student_id] => 2 
     ) 

    [2] => Array 
     (
      [amount] => 507400.00 
      [rows] => 214 
      [student_id] => 3 
     ) 
) 

我试图array_merge和array_merge_recursive但他们没有给我牛逼他预计结果,谢谢!

+0

我只是使用一个foreach()循环 – rtfm

+0

为什么你有这2个数组具有相同的相似性结构?你是从两张不同的表中选择它吗?我认为你应该在数据库级别做到这一点。 –

+0

是的,我知道,但我不能通过查询。所以我应该通过PHP来完成。顺便说一句我现在从Rahul得到了答案 –

回答

1

下面是简单的代码来解决问题,

count($arr) > count($arr0) ? ($greater = $arr AND $smaller = $arr0) : ($smaller = $arr AND $greater = $arr0); 
foreach ($greater as $key => &$value) { 
    foreach ($smaller as $key1 => &$value1) { 
     if($value['student_id'] == $value1['student_id']){ 
      $value['amount'] +=$value1['amount']; 
      $value['rows'] +=$value1['rows']; 
     } 
    } 
} 

检查输出here

+0

woahhh真棒,这很好,我得到了预期的结果,非常感谢! –

0

有关组合查询的评论可能是更好的方法。

SELECT student_id, sum(amount) as amount, sum(rows) as rows 
from students 
group by student_id; 

但是,如果您无法通过查询做到这一点,PHP本身不加阵列值加在一起(它没有意义)

这里是你必须做什么

function arrayMergeMatch(&$a, &$b) 
{ 
    foreach ($a as $key => $value) { 
     if (array_key_exists($key, $b)) { 
      // there's a matching index in both a & b 
      $a[$key] = [ 
       $a[$key]['amount'] += $b[$key]['amount'], 
       $a[$key]['rows'] += $b[$key]['rows'], 
       $a[$key]['student_id'], 
      ]; 
     } 
    } 
} 

$firstArray = $secondArray = []; 

$firstArray[0] = [ 
    'amount' => 21600.00, 
    'rows' => 2, 
    'student_id' => 1 
]; 


$secondArray[0] = [ 
    'amount' => 541990.00, 
    'rows' => 512, 
    'student_id' => 1, 
]; 

$secondArray[1] = [ 
    'amount' => 347480.00, 
    'rows' => 281, 
    'student_id' => 2, 
]; 

$secondArray[2] = [ 
    'amount' => 507400.00, 
    'rows' => 214, 
    'student_id' => 3, 
]; 

$firstArrayLength = count($x); 
$secondArrayLength = count($y); 

$combinedArray = null; 

if ($firstArrayLength > $secondArrayLength) { 
    // loop through x checking to see if there's a matching y 
    arrayMergeMatch($firstArray, $secondArray); 
    $combinedArray = $firstArray; 
} 
else { 
    // y is longer than or equal to x, so loop through y, looking for matching 
    // index in x 
    arrayMergeMatch($secondArray, $firstArray); 
    $combinedArray = $secondArray; 
} 

print_r($combinedArray);