如何在foreach循环中显示值

时间:2017-10-13 09:30:12

标签: php foreach slim

如何在 foreach 循环中获取值?我被困在代码中。 简而言之,这是我的代码:

    $students = $this->db->table('sys_user')
    ->select(['*'])
    ->leftjoin('sys_user_student', 'sys_user_student.user_id', '=', 'sys_user.user_id')
    ->leftjoin('sys_mf_section', 'sys_mf_section.section_id', '=',
               'sys_user_student.section_id')
    ->leftjoin('sys_mf_grade', 'sys_mf_grade.grade_id', '=', 'sys_mf_section.grade_id')
    ->where('sys_user.user_type_id', '4')
    ->where('sys_mf_section.section_id', $request->getParam('section_id'))
    ->where('sys_mf_grade.grade_id', $request->getParam('grade_id'))
    ->get()->toArray();     

    $result = array();
    foreach ($students as $key => $value) {
        $user_id = $value->user_id;

        $logs = $this->db->table('sys_user')
        ->where('user_id', $user_id)
        ->get()->toArray();

        $result[] = $logs;
    }

这是view文件。顺便说一下,我使用twig作为我的模板引擎

            <tbody>
            {% for student in students %}
            <tr>
                <td class="t-center">{{ student.identification_number }}</td>
                <td class="t-center">{{ student.last_name }}, {{ student.first_name }}</td>
                <td class="t-center">{{ student.gender }}</td>
                {% for results in result %}
                    <td class="t-center">{{ results.tapped_time | date('h:i:s A') }}</td>
                {% endfor %}
            </tr>
            {% endfor %}
            {% if students is empty %}
            <tr>
                <td colspan="4">No Data</td>
            </tr>
            {% endif %}
        </tbody>

1 个答案:

答案 0 :(得分:-1)

你(因此)有数组数组,类似于 [['name'=&gt; value,'name2'=&gt; value2],['name'=&gt; value,'name2'=&gt; value2]] 所以你必须使用2个foreach循环才能看到结果

foreach ($results as $index=>$array){
 foreach ($array as $k=>$v){
   echo $k." = ".$v."<br>";
 }
}

第二个答案(正确):

foreach ($students as $key => $value) {
        $user_id = $value->user_id;

        $logs = $this->db->table('sys_user')
        ->where('user_id', $user_id)
        ->get()->toArray();
         foreach ($logs as $l){
             $result[] = $l;
          }
    }

想想在另一步中做到这一点:

foreach ($logs as $l){
                 $result[$user_id][] = $l;
              }