php foreach循环无法正常工作

时间:2013-05-23 01:50:08

标签: php codeigniter loops

public function include_header( $h, $h_data ) {

    // Require header file
    if (isset($h) && !empty($h)) {
        $this->header_file = 'includes/header/'.$h;
    } else { return false; }

    // Pass optional array of parameters
    if (isset($h_data) && is_array($h_data) && !empty($h_data)) {

        // Loop through array & assign keys to appropriate class members
        foreach($h_data as $key => $val) {

            if ($key == 'doctype') { $this->doctype = $val; }
            if ($key == 'title') { $this->title = $val; }
            if ($key == 'meta') {
                // The meta key is should be an array in h_data
                // so, we'll have to loop through the meta array
                // in order to parse the individual meta elements.
                foreach($key as $meta_key => $meta_val) {
                    $this->error = $meta_key;
                }

            }

        }

    } else { return false; }

}

我正在尝试遍历多维数组,其中我有以下变量......

$ h_data [ '元'] [ 'individual_element']

我正在尝试遍历'meta',因此我可以访问每个单独的值,但我遇到了麻烦。请帮忙!提前谢谢!

2 个答案:

答案 0 :(得分:5)

foreach($key as $meta_key => $meta_val) {
    $this->error = $meta_key;
}

......应该是

foreach($val as $meta_key => $meta_val) {
    $this->error = $meta_key;
}

答案 1 :(得分:4)

 if ($key == 'meta') {
                // The meta key is should be an array in h_data
                // so, we'll have to loop through the meta array
                // in order to parse the individual meta elements.
                foreach($val as $meta_key => $meta_val) { //val not key
                    $this->error = $meta_key;
                }