Skip to content
Advertisement

Brackets instead of comma using foreach to create JSON with PHP

So I’m trying to create an open source file manager with php using ajax requests and, when i use json_encode my json response gets a close bracket for each array key.

This is the code (PHP):

<?php

$fileDirectory = "files/";
$fileArray = array_slice(scandir("$fileDirectory"), 3);
$fileSizeArray = array();

foreach($fileArray as $File){
    $fileSizeArray[$File] = filesize($fileDirectory.$File);
}

foreach($fileSizeArray as $File => $fileSize){
    echo json_encode ([
        $filesResponseArray[] = array(
            'fileName' => $File,
            'fileSize' => $fileSize
        )
    ]);
}

and this is the result:

[{"fileName":"61177d35527fd_w68FQFb.png","fileSize":10752}][{"fileName":"611780a39307c_1152265.jpg","fileSize":1383556}]

and i need this result

[{"fileName":"61177d35527fd_w68FQFb.png","fileSize":10752},{"fileName":"611780a39307c_1152265.jpg","fileSize":1383556}]

Advertisement

Answer

You encode to quickly. Try this:

<?php

$fileDirectory = "files/";
$fileArray = array_slice(scandir("$fileDirectory"), 3);
$fileSizeArray = array();

foreach($fileArray as $File){
    $fileSizeArray[$File] = filesize($fileDirectory.$File);
}

foreach($fileSizeArray as $File => $fileSize){
        $filesResponseArray[] = array(
            'fileName' => $File,
            'fileSize' => $fileSize
        );
}

echo json_encode($filesResponseArray);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement