php:如何将数组的值分配给默认表?

时间:2014-05-08 19:11:47

标签: arrays assign

这是我的代码:

$table=array("a","b","c","d");
$datas=array("a_1","c_8");

foreach($datas as $x => $data){
    $data=explode("_",$data);
    $keys[$x]=$data[0];
    $vals[$x]=$data[1];
}

$key=implode("</td><td>",$keys);
$val=implode("</td><td>",$vals);

echo"<table><tr><td>".$key."</td></tr><tr><td>".$val."</td></tr></table>";

打印出来像这样:

a   c
1   8

但我想要这个:

a   b   c   d
1       8   

1 个答案:

答案 0 :(得分:0)

你的问题是foreach,它目前只运行了2次,因为$ datas数组只有两个。尝试使用表Array,就像这样:

$table=array("a","b","c","d");
$datas=array("a_1","c_8");

foreach($table as $x => $tab){

    $var = "";

    foreach($datas as $data){

        $data = explode("_", $data);

        if($data[0]==$tab){
            $var = $data[1];
        }
    }

    $keys[$x]=$tab;
    $vals[$x]=$var;
}

$key=implode("</td><td>",$keys);
$val=implode("</td><td>",$vals);

echo"<table><tr><td>".$key."</td></tr><tr><td>".$val."</td></tr></table>";