Reputation: 49
I want to merge two array by checking the value of both the array in 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
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
)
)
Upvotes: 1
Views: 52
Reputation: 1219
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;
}
}
}
}
}
Upvotes: 0
Reputation: 1425
<?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);
Upvotes: 1