开发者

PHP question about multidimensional array

My array looks like this:

Array ( [Bob] => Red [Joe] => Blue )

But it could be any number of people, like this:

Array ( [Bob] => Red [Joe] => Blue [Sam] => Orange [Carla] => Yellow)

Basically I want PHP to take this array and echo it so that it comes out looking like:

Bob - Red
Joe - Blue
Sam - Orange
Carla - Yellow

I know I need to loop through the array, this is what I tried:

for ($row = 0; $row < count($arr开发者_运维问答ay); $row++) {
echo $array[0] . " - " . $array[1];
}

I get the following error: Undefined offset: 0, Undefined offset: 1

I realize that this doesn't work because I'm trying to use index's when the values of the array are strings. Is there any way I can use positional index's like this with a multidimensional array that only contains strings?

Thanks


What you want is a foreach loop.

foreach ($array as $key => $value) {
    echo $key . ' - ' . $value;
}

(if you want a newline, append "\n" to the end)

Your array is actually not multidimensional. An example of that would be

array(
    array(
        'bob',
        'tom'
    )
);

Note the array within the array.

Your array is generally called an associative array.


Without re-checking my php knowledge:

foreach($array as $key => $value) {
    echo "$key - $value<br />\n";
}


You need a foreach

<?php 
$arr = array("bob" => "red", "paul" => "blue", "preo" => "yellow", "garis" => "orange");
foreach ($arr as $key => $value) {
    echo $key ." - ".$value."<br />";
}
?>

Will print:

bob - red
paul - blue
preo - yellow
garis - orange

By the way, it is a associative array, not a multidimensional one, which is more something like:

$array[1][0][3]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜