I am attempting to convert the MySQL table into an array using PHP. Each Listing ID in the Image Table has at least one Image ID, however the total number of Image IDs may vary.
Image Table:
|Listing ID | Image ID |
| 1234 | 1 |
| 1234 | 2 |
| 1234 | 3 |
| 1235 | 1 |
| 1235 | 2 |
Essentially, I would like to transform the Image Table into an array with a key value pair like follows:
array([0] 1234 => /FilePath/1234-1::/FilePath/1234-2::/FilePath/1234-3, [1] 1235 => /FilePath/1235-1::/FilePath/1235-2, ...)
I've been able to write some code that, for the most part, accomplishes this task. However, there are some issues.
The main issue with my code is that the $lid array and $prod array do not contain the same amount of elements ($prod contains one more element than $lid). This is baffling to me since they are pulling data from the same Image Table and therefore should have the same number of elements.
My code:
//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);
A secondary issue is that PHP returns the following message whenever the foreach loop is run:
Notice: Undefined offset: 2789 in C:\mypath\getimage.php on line 78
Row 2789 is the last row in the image table, so I think this error notice may be related to the fact that $lid and $prod have difference of the number of elements by 1.
Any suggestions are much appreciated. Also, let me know if you can think of a more efficient way to accomplish this task.
Thanks,