2009-12-21 77 views
0

我有一個數組,我似乎無法取回我的數據。我想要的是每個名稱(test1 ...)都有多個與它們關聯的網址。如果你看最後一個測試(test5),有2個url,但是這個foreach循環只給了我一個。爲什麼?PHP數組foreach問題

這裏是數組結構和我的foreach循環。

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>'; 
    } 
} 

回答

2

你有你的第二個以後的foreach一個分號:foreach(...); {...這不應該存在。下面的代碼按照您的預期工作。

<?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>'; 
    } 
    } 
+0

OMG ......我無法相信我錯過了。 :) 謝謝! – John 2009-12-21 04:38:58

0

我只是複製你提供的代碼,它給了我正確的結果:

 
$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.'
'; } }

這是我得到的結果:

測試1 - http://www ....
test2 - http://www ....
test3 - http://www ....
TEST4 - http://www ....
TEST5 - http://www.yahoo.com
TEST5 - http://www.google.com