如何在php中显示另一个数组中的数组名称

时间:2014-11-18 22:35:51

标签: php

我是php新手,我有一个小问题。

这是我的数组

$cars=array( "1234"=> array("Toyota","100","2","white"),
            "2468"=> array("Mazda","1000","0","red"),
            "4587"=> array("Mercedes","200","0","green")
                        ); 
$_SESSION['cars']=$cars;

元素1234,2468和4587基本上是汽车的注册号,我的任务是将这些注册号插入表中。

if( isset($_SESSION['cars']))
        {
        foreach($_SESSION['cars'] as $key)
        {?>
                <tr><td><?php echo $key?></td></tr>

这是我做的,但它给我一个错误说通知:数组到字符串转换。

谁能告诉我怎么做?我将不胜感激

2 个答案:

答案 0 :(得分:2)

这应该适合你:

if( isset($_SESSION['cars'])) {

    foreach($_SESSION['cars'] as $key => $v)
        echo "<tr><td>" . $key . "</td></tr><br />";
}

编辑:

应该可以看到这个例子:

<?php

    session_start();

    $cars = array(
                "1234"=> array("Toyota","100","2","white"),
                "2468"=> array("Mazda","1000","0","red"),
                "4587"=> array("Mercedes","200","0","green")
            ); 

    $_SESSION['cars'] = $cars;

    if( isset($_SESSION['cars'])) {

        foreach($_SESSION['cars'] as $key => $v)
            echo "<tr><td>" . $key . "</td></tr><br />";
    }

?>

输出:

1234
2468
4587

答案 1 :(得分:1)

<?php
        $cars=array( "1234"=> array("Toyota","100","2","white"),
            "2468"=> array("Mazda","1000","0","red"),
            "4587"=> array("Mercedes","200","0","green")
        );
        $_SESSION['cars']=$cars;
        //In separated file
        if(!isset($_SESSION)) session_start();
        if( isset($_SESSION['cars']))
        {
            foreach($_SESSION['cars'] as $key => $value)
            {
                echo "<tr><td> $key </td></tr>";
            }
        }
?>