我的foreach循环中多维数组的错误是什么?

时间:2013-05-08 09:05:47

标签: php arrays multidimensional-array associative-array

以下是我的多维数组$prev_map_data

Array
(
    [0] => Array
        (
            [class_id] => 2
            [class_name] => II
            [class_checked] => 1
            [class_subjects] => Array
                (
                    [0] => Array
                        (
                            [cs_map_id] => 81
                            [subject_name] => 11 Engllish
                            [subject_checked] => 1
                            [teacher_cs_id] => 81
                        )

                )

        )

    [1] => Array
        (
            [class_id] => 3
            [class_name] => III
            [class_checked] => 1
            [class_subjects] => Array
                (
                    [0] => Array
                        (
                            [cs_map_id] => 155
                            [subject_name] => Hidi
                            [subject_checked] => 1
                            [teacher_cs_id] => 155
                        )

                    [1] => Array
                        (
                            [cs_map_id] => 156
                            [subject_name] => 11 Maths
                            [subject_checked] => 1
                            [teacher_cs_id] => 156
                        )

                    [2] => Array
                        (
                            [cs_map_id] => 157
                            [subject_name] => 11 Science
                            [subject_checked] => 1
                            [teacher_cs_id] => 157
                        )

                )

        )

)

我希望逐个获取密钥[cs_map_id]中的所有值,并将值推送到数组$data中。但得到警告

Warning: Invalid argument supplied for foreach()

我不明白我的代码有什么问题。任何人都可以帮我改进我的代码并将值附加到新数组吗?提前致谢。我的代码如下:

$prev_map_data  = $objTeacherClassesSubjects->GetClassSubjectMappingsbyTeacherId ($request, $teacher_class_subjects_error_messages);
//print_d($prev_map_data);
$data = array();
foreach($prev_map_data as $map_id){
    foreach($map_id as $ast){
        foreach($ast as $tp){
            //print_p($tp);
            $tp['cs_map_id'];
            array_push($data,$tp['cs_map_id']);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您无条件地在数组中挖掘不是自身数组的项目。这样做:

foreach($prev_map_data as $map_id){
    foreach($map_id['class_subjects'] as $subject){
        $data[] = $subject['cs_map_id'];
    }
}

答案 1 :(得分:0)

使用此

$arr = array();

foreach($prev_map_data as $map_id){
   $i = 0;
   foreach($map_id['class_subjects'] as $val) {

       $arr[$i] = $val['cs_map_id'];
       $i++;
   }
}