I am trying to compare two arrays and update specific array values based on conditions.
Getting attendance array of absent students:
$array1 =
array(
array("student_id" => "2",
"date" => "2016-04-24"),
array("student_id" => "6",
"date" => "2016-04-24"));
$attendance = json_decode(json_encode($array1));
Getting student list array of all students:
$array2 =
array(
array("student_id" => "1",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "2",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "3",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "6",
"Reason" => "1",
"date" => "2016-04-24"));
$students = json_decode(json_encode($array2));
Taking out only student IDs of absent students:
foreach($attendance as $att)
{ $atts[] = $att->student_id;}
Here I am trying to find out if any of the students ID in student array matches with ID in absent array. If ID is present then I will update the Reason as "1". Else will make the reason as 0
for ($i = 1; $i <= count($students); $i++) {
if(in_array($atts[$i],$students))
{
$students->Reason='1';
}
else
{
$students->Reason='0';
}
}
echo '<pre>',print_r($students,1),'</pre>';
Here I am unable to update student array with "reason" values.
If you just want to compare student_id
from array1
with student_id
from array2
, and set Reason
in array2
if they correspond to each other, use this :
foreach ($array1 as $key1 => $value1) {
foreach ($array2 as $key2 => $value2) {
if ($value1['student_id'] == $value2['student_id']) {
$array2[$key2]['Reason'] = 1;
} else if ($array2[$key2]['Reason'] != 1) {
$array2[$key2]['Reason'] = 0;
}
}
}