user2987364
user2987364

Reputation: 35

PHP: Printing strings written in an array within an array

I want to print strings inside the array within the array, so it would look more like this:

bob: ball, bat, car

daniel: bat, bear, car

and less like this:

Bob: Array ( [0] => ball [1] => bat [2] => car )

Daniel: Array ( [0] => bat [1] => bear [2] => car )

<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>

I tried many things, but I always get the 'string to array conversion' error.

Upvotes: 1

Views: 69

Answers (2)

Tim
Tim

Reputation: 8606

replace print_r ($b["toy"]); with:

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

Upvotes: 1

Parixit
Parixit

Reputation: 3855

You have to make string from array, so that use implode() and display it as a string like following.

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

Upvotes: 1

Related Questions