简体   繁体   English

php无法更新特定的数组值

[英]php unable to update specific array value

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.在这里,我试图找出学生数组中的任何学生 ID 是否与缺失数组中的 ID 匹配。 If ID is present then I will update the Reason as "1".如果存在 ID,那么我会将原因更新为“1”。 Else will make the reason as 0否则会使原因为 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 :如果您只想将array1中的student_idarray2 student_id进行比较,如果它们彼此对应,则在array2设置Reason ,请使用以下命令:

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

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

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