0

多維數組一直沒能找到一個直接的答案尚未..我的數組$ sitematches:打印從preg_match_all

if (preg_match('/<start>(.*?)<finish>/s', $source, $matches)) { 
    if (preg_match_all('/<a\s[^>]*href=\"([^\"]*)\"[^>]*>(.*)<\/a>/siU', $matches[1], $sitematches)); { 
    print_r($sitematches); 
    } 
} 

生產:

Array 
(
    [0] => Array 
     (
      [0] => <A HREF="http://site1.com">aaa</A> 
      [1] => <A HREF="http://site2.com">bbb</A> 
      [2] => <A HREF="http://site3.com">ccc</A> 
      [3] => <A HREF="http://site4.com">ddd</A> 
     ) 

    [1] => Array 
     (
      [0] => http://site1.com 
      [1] => http://site2.com 
      [2] => http://site3.com 
      [3] => http://site4.com 
     ) 

    [2] => Array 
     (
      [0] => aaa 
      [1] => bbb 
      [2] => ccc 
      [3] => ddd 
     ) 

) 

我怎麼能輸出:

1 - aaa - http://site1.com 
2 - bbb - http://site2.com 
3 - ccc - http://site3.com 
4 - ddd - http://site4.com 

回答

0

用foreach另一個possibilty是:需要

foreach ($sitematches[1] as $key => $url) 
    print "$key - {$sitematches[2][$key]} - $url\n"; 

但至少有一個直接數組訪問。

+0

很好,避免計數因此效率更高,對不對? – Adrian33 2013-04-06 12:19:35

+0

我沒有知道,但我認爲這很可能...寫出你自己的microbenchmark ;-) – bwoebi 2013-04-06 12:21:11

+0

謝謝你回答這個問題,應該讓你爲更困難的事情變暖。 – Adrian33 2013-04-06 12:25:41

1
for ($i = 0; $i < count($sitematches[0]); $i++) 
    print "$i - {$sitematches[2][$i]} - {$sitematches[1][$i]}\n"; 

簡單地得到大小(計數($ S itematches [0])),然後遍歷數組。

+0

的作品。出於好奇,是否有任何方法來避免計數和使用:foreach($ sitematches .... – Adrian33 2013-04-06 11:53:46

+0

我已經添加了另一個答案。 – bwoebi 2013-04-06 12:02:37