[英]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.