PHP:打印在数组中以数组形式写入的字符串

时间:2013-11-13 11:17:41

标签: php arrays

我想在数组中的数组内打印字符串,所以看起来更像是这样:

鲍勃:球,蝙蝠,汽车

丹尼尔:蝙蝠,熊,车

而不是这样:

鲍勃: 排列 (     [0] =>球     [1] =>蝙蝠     [2] =>汽车 )

丹尼尔: 排列 (     [0] =>蝙蝠     [1] =>熊     [2] =>汽车 )

<html>
<head>
<?php
$b;

$school=array(
"14"=>array("name"=>"Bob","toy"=>array("ball","bat","car")),
"23"=>array("name"=>"Daniel","toy"=>array("bat","bear","car")),
"31"=>array("name"=>"Tom","toy"=>array("bicycle","ball")),
"44"=>array("name"=>"Tim","toy"=>array("train","puzzle","ball","stick")),
"53"=>array("name"=>"Barbara","toy"=>array("bear", "car"))
);


foreach($school as $b)
{
echo $b["name"];
echo '<pre>';
print_r ($b["toy"]);
echo '</pre>';
}
?>
</head>
</html>

我尝试了很多东西,但我总是得到'字符串转换'错误。

2 个答案:

答案 0 :(得分:1)

你必须从数组中创建字符串,以便使用implode()并将其显示为如下的字符串。

foreach($school as $b)
{
    echo "$b[name] : ".implode(',',$b["toy"]);
}

答案 1 :(得分:1)

print_r ($b["toy"]);替换为:

echo implode(', ', $b["toy"] );