【问题标题】:Print multi-dimensional array from preg_match_all从 preg_match_all 打印多维数组
【发布时间】:2013-04-06 11:42:54
【问题描述】:

还没有找到直接的答案.. 我的数组 $sitematches:

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

【问题讨论】:

    标签: php multidimensional-array html-parsing echo preg-match-all


    【解决方案1】:
    for ($i = 0; $i < count($sitematches[0]); $i++)
        print "$i - {$sitematches[2][$i]} - {$sitematches[1][$i]}\n";
    

    只需获取大小 (count($sitematches[0])),然后遍历数组。

    【讨论】:

    • 有效。出于好奇,有什么办法可以避免计数并使用:foreach($sitematches....
    • 我已经添加了另一个答案。
    【解决方案2】:

    foreach 的另一种可能性是:

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

    但至少需要一次直接数组访问。

    【讨论】:

    • 我不知道,但我认为这很可能......编写你自己的微基准 ;-)
    • 感谢您回答这个问题,应该让您为更困难的事情做好准备。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2016-11-28
    相关资源
    最近更新 更多