PHP:使用两个foreach循环分解两个分隔符

时间:2012-08-16 10:18:59

标签: php loops foreach explode

我试图通过使用两个分隔符<>"\n"进行爆炸来获取两个foreach循环但是会出错。 Warning: Invalid argument supplied for foreach()

这是我的代码

<?php

    $specifications = $scooter_meta->get_the_value('specifications');

    $titles = explode('<>', $specifications);

    $descs = explode("\n", $specifications);

    echo '<dl>';

    foreach($titles as $title => $descs){

        echo '<dt>' . $title . '</dt>';

        foreach($descs as $desc){
            echo '<dd>' . $desc . '</dd>';
        }

    }

    echo '</dl>';

?>

进入textarea的值是这样的Title here<>this is the first scooter ever made. Title here 2<>another line for specification实际上我想让它像<title 1> here detail text

非常感谢

3 个答案:

答案 0 :(得分:2)

$descs变量不是数组,因为第一个foreach循环设置了$descs

见这一行:

foreach($titles as $title => $descs){

答案 1 :(得分:2)

实际上你应该做这样的事情

<?php

$specifications = $scooter_meta->get_the_value('specifications');

$descs = explode("\n", $specifications);

echo '<dl>';

foreach($descs as $desc){

    $title = explode('<>', $desc);

    echo '<dt>' . $title[0] . '</dt>';
    for($i=1; $i<=count($title); $i++){
        echo '<dd>' . $title[$i] . '</dd>';
    }

}

echo '</dl>';

?>

答案 2 :(得分:1)

$specifications = $scooter_meta->get_the_value('specifications');

$titles = explode('<>', $specifications);

echo '<dl>';

foreach($titles as $title => $descs){

    echo '<dt>' . $title . '</dt>';

    $descs = explode("\n", $descs);

    foreach($descs as $desc){
        echo '<dd>' . $desc . '</dd>';
    }

}

echo '</dl>';