繁体   English   中英

PHP数组/ array_unique混淆

[英]PHP array/array_unique confusion

我创建了一个图像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>';

}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM