0

以下是我的多维数组,名为$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']);
        }
    }
}
4

2 回答 2

2

您正在无条件地挖掘本身不是数组的项目的数组。改为这样做:

foreach($prev_map_data as $map_id){
    foreach($map_id['class_subjects'] as $subject){
        $data[] = $subject['cs_map_id'];
    }
}
于 2013-05-08T09:08:54.413 回答
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++;
   }
}
于 2013-05-08T09:08:43.133 回答