我試圖將MySQL錶轉換爲使用PHP的數組。圖像表中的每個商品ID至少有一個圖像ID,但圖像ID的總數可能有所不同。PHP爲每個循環創建不等數組
圖片表:
|Listing ID | Image ID |
| 1234 | 1 |
| 1234 | 2 |
| 1234 | 3 |
| 1235 | 1 |
| 1235 | 2 |
從本質上講,我想映像表變換成陣列與一個鍵值對等如下:
array([0] 1234 => /FilePath/1234-1::/FilePath/1234-2::/FilePath/1234-3, [1] 1235 => /FilePath/1235-1::/FilePath/1235-2, ...)
我已經能夠寫一些代碼大部分完成了這項任務。但是,有一些問題。
我的代碼的主要問題是$ lid數組和$ prod數組不包含相同數量的元素($ prod包含多於$ lid的元素)。這對我來說很困惑,因爲他們從相同的圖像表中提取數據,因此應該具有相同數量的元素。
我的代碼:
//Set document path
$target_path = realpath($_SERVER['DOCUMENT_ROOT']). "\mypath\image\uploads\\";
//Query to download all listing IDs in Markers table
$query = $db->query("SELECT * FROM image");
while ($row = $query->fetch(PDO::FETCH_BOTH)) {
$temp[] = $row;
}
foreach($temp as $i=>$v){
$line = $target_path.$v['L_ListingID']."-".$v['L_ImageID'].".jpg";
if($temp[$i]['L_ListingID']==$temp[$i+1]['L_ListingID']){
//appending '::' to each string in the $prod array
$prod[] = $line."::";
}else{
// * will serve as the delimiter in the $prod array
$prod[] = $line."*";
//Add each listing ID into Listing Array
$lid[] = $v['L_ListingID'];
}
}
//Convert the array into a big string
$bigString = implode("", $prod);
//Chop up the big string into sections delimited by '*' and insert into 'prod' array
$prod = explode("*",$bigString);
//Combine $lid array with $prod array
$combo = array_combine($lid, $prod);
次要問題是,PHP返回每當foreach循環運行以下消息:
注意:未定義偏移量:2789在C:\ mypath中\的getImage .php 78行
行2789是圖像表中的最後一行,所以我認爲這個錯誤通知可能與$ lid和$ prod有差異的元素數量爲1.
任何建議,非常感謝。另外,讓我知道你是否可以想到一個更有效的方法來完成這項任務。
感謝,
這段代碼產生不同數量$督促和$蓋之間的元素。 – AME