1

我有一个html数组结构..

我用 foreach 循环输出这个数组。(在 get_output 函数内部)

是否可以在不使用 foreach 的情况下输出结果?

$schema = array(
    array(
        'tag' => 'div',
        'class' => 'lines',
        array(
            'tag' => 'div',
             array(
                'tag' => 'span',
                'style' => 'margin:10px; padding:10px',
                'key' => '$key-countryname',
            ),
            'key' => '$value-country',
        ),
        array(
            'tag' => 'div',
             array(
                'tag' => 'span',
                'style' => 'margin:10px; padding:10px',
                'key' => '$key-countryname',
            ),
            'key' => '$value-country',
        ),
    )
);

我的功能是使用 foreach 循环输出结果

function get_output($schema, $t = -2){
    $t++; $tag = ""; $atts = array(); $keys = array(); $code = array();

    foreach($schema as $k => $v){        
        if(is_array($v)){
            $keys[] = get_output($v, $t);
        } else {
            switch($k){
                case "tag": $tag = $v; break;
                case "key": $keys[] = $v; break;
                case "type": break;
                default: $atts[$k] = $v; break;
            }
        }    
    }
    if(0 < $t){ $code[] = "\n".str_repeat("\t", $t); }
    if($tag){
        $code[] = "<$tag"; foreach($atts as $k=>$v){ $code[] = ' '.$k.'="'.$v.'"'; } $code[] = ">";
        $code = array(implode('', $code));
    }
    foreach($keys as $k){ $code[] = $k; } 
    if($tag){
        $code[] = "\n".str_repeat("\t", $t);
        $code[] = '</'.$tag.'>'; 
    }
    //print_r($code);
    return implode("", $code);
}
4

1 回答 1

1

while并且for是循环数组的完全有效方法:

$a = array(1,2,3); // indexed
$b = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
); // associative

echo '$a indexed with "for": <br />';
for ($i = 0; $i < count($a); $i++) {
   echo $a[$i] . '<br />';
}
echo '$a indexed with "while": <br />';
$i = 0; // reset counter
while ($i < count($a)) {
   echo $a[$i] . '<br />';
   $i++;
}

echo '$b assoc with "for": <br />';
for ($i = 0; $i < count($a); $i++) {
   echo key($b) . ' => ' . current($b) . '<br />';
   next($b); // step forward
}
echo '$b assoc with "while": <br />';
reset($b); // rewind array cursor to start
while ($value = current($b)) {
   echo key($b) . ' => ' . $value . '<br />';
   next($b); // step forward
}

此外,正如您已经在第二个代码片段中实现的那样,可以使用递归循环多维数组(尽管与嵌套循环相比,它消耗更多内存)

于 2013-08-25T08:53:53.567 回答