Best way to output PHP array into csv file

I am currently working on a simple task yet a bit tricky. My task is to read all the images from the directory and write them into CSV file. So, when I read the directory I get the array list of images filename data will look like below:

array (
    '13763',
    '13763-1',
    '13763-2',
    '13764',
    '13765',
    '13765-1',
);

I wanted this data to be exported into csv file which looks like below:
image

So, I am going through the foreach loop as $image which gives me each element and each loop I am checking the string has ‘-’ character or not. If it has no ‘-’ character than I assign $currentId = $image but if it has ‘-’ then I assign $additionalImage .= ‘, ‘.$image.’.jpg’. But the problem is I only want to insert one row if it has additional images ‘13763.jpg, 13763-1.jpg, 13763-2.jpg’. Below is my code what I have done so far.

$currentId = '';
$additionalImages = '';
$addId = '';

foreach ($images as $image) {
   
    if (strpos($image, '-') == FALSE) {
        $currentId = $image;
        $additionalImages = $image.'.jpg';
    }

    if (strpos($image, '-') != FALSE) {
        $addId = substr($image, 0, strpos($image, '-'));
        $additionalImages .= ', '.$image.'.jpg';
    }

    
    // insert into csv file

}

Take a look at the fputcsv() function in PHP.

Sorry @SamA74 but this is not the issue I currently have. The issue is I could not able to generate single row from the array which I mentioned already.

I don’t understand the problem. It would be easier to follow if the spreadsheet you showed actually corresponded to the data in your array.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.