php无法更新特定的数组值

时间:2016-04-28 10:07:24

标签: php

我正在尝试比较两个数组并根据条件更新特定的数组值。

获得缺席学生的出席情况:

$array1 = 
    array(
    array("student_id" => "2",
        "date" => "2016-04-24"),
    array("student_id" => "6",
        "date" => "2016-04-24"));
$attendance = json_decode(json_encode($array1));

获取所有学生的学生名单:

$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));

只取出缺席学生的学生证:

foreach($attendance as $att) 
{   $atts[] = $att->student_id;}

这里我试图找出学生数组中的任何学生ID是否与缺席数组中的ID匹配。如果ID存在,那么我将更新原因为" 1"。否则将原因归结为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>';

在这里,我无法用&#34;原因&#34;更新学生数组。值。

1 个答案:

答案 0 :(得分:1)

如果您只想将student_id中的array1student_id中的array2进行比较,并在Reason中设置array2彼此,用这个:

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