2012-12-28 30 views
0

我試圖將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.

任何建議,非常感謝。另外,讓我知道你是否可以想到一個更有效的方法來完成這項任務。

感謝,

回答

1

使用此算法,您必須爲最後一行創建一個特殊情況(這會導致Ninsuo指示的通知「未定義偏移量」)。

下面的算法應該建立你所期望的數組:

$combo = array(); 
foreach($temp as $v){ 
    $line = $target_path.$v['L_ListingID']."-".$v['L_ImageID'].".jpg"; 
    $key = $v['L_ListingID']; 
    if (array_key_exists($key, $combo)) { 
     // Append 
     $combo[$key] .= '::' . $line; 
    } else { 
     // Create key 
     $combo[$key] = $line; 
    } 
} 
2

對於這個問題:

注意:未定義抵消:2789在C:\ mypath中\ getimage.php上線78

這是因爲你正在做:

if($temp[$i]['L_ListingID']==$temp[$i+1]['L_ListingID']){ 

您需要$i+1即使您的foreach是最後一個元素。

你需要檢查如果$i+1鍵存在,通過替換它:

if(array_key_exists($i+1, $temp) && ($temp[$i]['L_ListingID']==$temp[$i+1]['L_ListingID'])){ 

對於「主」的問題,你的代碼是太複雜了。如果你開始搖動字符串和數組,就會出現錯誤。只能使用字符串或只使用數組,但不能同時使用,這將更難以維護。

$bigstring = ''; 
$lid = array() 
foreach($temp as $i=>$v){ 
    $bigstring .= $target_path.$v['L_ListingID']."-".$v['L_ImageID'].".jpg"; 
    if(array_key_exists($i+1, $temp) && ($temp[$i]['L_ListingID']==$temp[$i+1]['L_ListingID'])) { 
     $bigstring .= "::"; 
    }else{ 
     $bigstring .= "*"; 
    } 
    if (!in_array($v['L_ListingID'], $lid)) { 
     $lid[] = $v['L_ListingID']; 
    } 
} 

最後一件事:在變量上使用數組運算符之前,這是初始化數組的好習慣。

$temp = array(); 
while ($row = $query->fetch(PDO::FETCH_BOTH)) { 
    $temp[] = $row; 
} 

否則,PHP會拋出E_NOTICEs。

+0

這段代碼產生不同數量$督促和$蓋之間的元素。 – AME

相關問題