duandao2083 2016-04-28 02:07
浏览 39
已采纳

php无法更新特定的数组值

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.

展开全部

  • 写回答

1条回答 默认 最新

  • dongzhong9055 2016-04-28 02:59
    关注

    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;
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部