請看下面的代碼:
在處理之前有兩個數組arrTitle和arrHref,
其中arrTitle內容如下:
arrHref內容如下:
//將title數組中首元素取出,作為欄目標題foreach ($arrTitle as &$title) { $text [] = $title[0]; unset($title[0]);}//將href數組中首元素取出,作為欄目urlforeach ($arrHref as &$href) { $url [] = $href[0]; unset($href[0]);}print_r($arrTitle);//重新組織title項$title = array_combine($text, $url);print_r($arrTitle);die;
運行上面的PHP代碼,把title和href中每項的首元素取出並去除,然而問題來了,在執行array_combine之前,$arrTitle是這樣的:
然而在執行array_combine之後,$arrTitle變成了這樣:
為什麼,$arrTitle的最後一個元素變成了array_combine()的結果,而array_combine()函數並沒有對$arrTitle執行了修改?
回複內容:
請看下面的代碼:
在處理之前有兩個數組arrTitle和arrHref,
其中arrTitle內容如下:
arrHref內容如下:
//將title數組中首元素取出,作為欄目標題foreach ($arrTitle as &$title) { $text [] = $title[0]; unset($title[0]);}//將href數組中首元素取出,作為欄目urlforeach ($arrHref as &$href) { $url [] = $href[0]; unset($href[0]);}print_r($arrTitle);//重新組織title項$title = array_combine($text, $url);print_r($arrTitle);die;
運行上面的PHP代碼,把title和href中每項的首元素取出並去除,然而問題來了,在執行array_combine之前,$arrTitle是這樣的:
然而在執行array_combine之後,$arrTitle變成了這樣:
為什麼,$arrTitle的最後一個元素變成了array_combine()的結果,而array_combine()函數並沒有對$arrTitle執行了修改?
**$title** = array_combine($text, $url);
這裡的$title 和上面迴圈裡的 $title 重名,改個名字就好了。php 裡沒有塊範圍。
此bug已經解除,感謝 @whyreal 指出重名問題。
由於在foreach迴圈中,以引用方式遍曆數組,當迴圈結束時,$title指向了$arrTitle的最後一組元素。
由於PHP沒有塊級範圍,在$title = array_combine($arr1, $arr2),之後這個$title同時修改了它指向的$arrTitle的最後一組元素,由此產生了bug。
修改後面$title的名稱解除此bug。