开发者

PHP array foreach issue

I have an array that I can't seem to get my data back out of. What I would like is for each name (test1...) to have multiple urls associated with them. If you look at the last test (test5), there are 2 urls but this foreach loop only gives me one. Why?

Here is the array structure and my foreach loop.

Array
(
    [test1] => Array
        (
            [0] => http://开发者_开发技巧www....
        )

    [test2] => Array
        (
            [0] => http://www....
        )

    [test3] => Array
        (
            [0] => http://www....
        )

    [test4] => Array
        (
            [0] => http://www....
        )

    [test5] => Array
        (
            [0] => http://www.yahoo.com
            [1] => http://www.google.com
        )

)

foreach($source as $name=>$url)
{
    foreach($url as $_url);
    {
      echo $name.' - ';
      echo $_url.'<br>';
    }
}


You have a semicolon after your second foreach: foreach(...); {... which shouldn't be there. The code below works as you would expect.

<?php
  $source = array(
    'test5' => array(
      "http://www.yahoo.com",
      "http://www.google.com"
    )
  );

  foreach ($source as $name => $url) {
    foreach($url as $_url) {
      echo $name.' - ';
      echo $_url.'<br>';
    }
  }


I just copied the code that you supplied and it gave me to correct results:

$array = array
(
    'test1' => Array
        (
             'http://www....'
        ),

    'test2' => Array
        (
            'http://www....'
        ),

    'test3' => Array
        (
             'http://www....'
        ),

    'test4' => Array
        (
             'http://www....'
        ),

    'test5' => Array
        (
             'http://www.yahoo.com',
             'http://www.google.com'
        )

);

foreach($array as $name=>$url)
{
    foreach($url as $_url)
    {
      echo $name.' - ';
      echo $_url.'
'; } }

These are the results i got:

test1 - http://www....
test2 - http://www....
test3 - http://www....
test4 - http://www....
test5 - http://www.yahoo.com
test5 - http://www.google.com

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜