【问题标题】:PHP array/array_unique confusionPHP array/array_unique 混淆
【发布时间】:2012-08-05 09:29:28
【问题描述】:

我创建了一组图片 URL:

$matches = array();

preg_match_all('#(http://[^\s]*?\.jpg)#i',$html, $matches);

$matches2 = array_unique($matches); // get unique

echo "there are ".count($matches2)." items!";

print_r($matches);

计数显示我有一个结果,但是结果如下:

there are 1 items!

Array ( [0] => 

Array ( 
[0] => http://testmenow.com/248472104410838590_J3o6Jq50_b.jpg 
[1] => http://testmenow.com/cirrow_1338328950.jpg 
[2] => http://testmenow.com/madi0601-87.jpg 
[3] => http://testmenow.com/swaggirll-4.jpg 
[4] => http://testmenow.com/erythie-35.jpg ))

随后,当我尝试从 URL 打印出每张图片时,我只得到数组中的第一个:

foreach ($matches2 as $image) {

echo '<img src='.$image[0].' width=200 height=200>';

}

我需要能够分别打印每个数组项 - 我想我在某处混淆了一些东西,但两个小时后......仍然在同一个地方

【问题讨论】:

    标签: php arrays array-unique


    【解决方案1】:

    preg_match_all 为每个子匹配返回一个数组。这意味着$matches[0] 是包含您预期结果的数组。 您的代码应如下所示:

    preg_match_all('#http://[^\s]*?\.jpg#i',$html, $matches);
    $matches2 = array_unique($matches[0]); // get unique
    echo "there are ".count($matches2)." items!";
    
    foreach ($matches2 as $image) {
        echo '<img src='.$image.' width=200 height=200>';
    }
    

    您可以省略正则表达式中的括号,因为这已经匹配。

    【讨论】:

    • 非常感谢 - 为此 +1 - 但是,回显行应为: echo '';因为打印图像 [0] 只打印字母 h
    • @DarrenSweeney 你是正确的复制了它并错过了它:) 谢谢。
    猜你喜欢
    • 2020-06-20
    • 1970-01-01
    • 2019-06-18
    • 2017-10-28
    • 1970-01-01
    • 2011-09-10
    • 2021-02-25
    • 2013-05-26
    • 2010-11-05
    相关资源
    最近更新 更多