简体   繁体   English

如何通过检查两个数组的一个元素的键值对相同​​将一个数组的内容合并到另一个数组

[英]How to merge contents of one array to another array by checking key value pair of one element of both the array are same

I want to merge two array by checking the value of both the array in php 我想通过检查PHP中两个数组的值来合并两个数组

Sample array is like this, first array 示例数组是这样的,第一个数组

 Array
(
  [0] => Array
      (
         [studentName] => XYZ
         [studentId] => 690
         [rollNo]    => 36    
      )

  [1] => Array
     (
         [studentName] => ABC
         [studentId] => 729
         [rollNo]    => 37    
     )
)

My second array is: 我的第二个数组是:

Array
 (
  [0] => Array
    (
        [attendanceCode] => 13
        [studentId] => 690
    )

  [1] => Array
    (
        [attendanceCode] => 14
        [studentId] => 729
    )
)

No i want to add [attendanceCode] key and value to the first array only if [studentId] of both the arrays are same 不,仅当两个数组的[studentId]相同时,我才想将[attendanceCode]键和值添加到第一个数组

My sample out put should be as follows: 我的样本输出应该如下:

 Array
(
  [0] => Array
      (
         [studentName] => XYZ
         [studentId] => 690
         [rollNo]    => 36
         [attendanceCode] => 13
      )

  [1] => Array
     (
         [studentName] => ABC
         [studentId] => 729
         [rollNo]    => 37 
         [attendanceCode] => 14   
     )
)
<?php
   $combined_array = array();
   foreach($array1 as $key => $a)
   {
      $combined_array[] = array_merge($array1[$key], $array2[$key]);
   }
?>

or do 或做

$combined_array = array_merge_recursive($array1, $array2);

Try below code, by using this you do not need to worry about indexing of the arrays 尝试下面的代码,使用此代码,您不必担心数组的索引编制

    <?php
$arr1 = array(
            array('studentName'=> 'XYZ',
            'studentId'=> 690 ,
            'rollNo'=> 36,
            ),
            array('studentName'=> 'ABC',
            'studentId'=> 729 ,
            'rollNo'=> 37,
            )
        );

$arr2 = array(
            array('attendanceCode'=> '14',
            'studentId'=> 729 ,
            ),
            array('attendanceCode'=> '13',
            'studentId'=> 690
            )

        );

$combined_array = array();
if(is_array($arr1)){
    foreach($arr1 as $key=>$val){
        if(is_array($arr2)){
            foreach($arr2 as $k1=>$v1){     
                if($v1['studentId'] == $val['studentId']){
                    $combined_array[] = array_merge($val, $v1);
                    break;
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM