Ben
Ben

Reputation: 27

Loop variable into an Array then encode it into 1 JSON

I had been searching for a while, and I can't seem to find a solution for my problem, so I created an account.

My situation is as below.

  1. I am doing a for loop upload image form.

  2. Every time it loops, it will have 1 $Listingid.photo

  3. I would like to add all the $Listingid.photo into an array, then package it into 1 JSON. and echo it.

And I am not very sure how to approach it. At the moment it is creating 1 JSON response per loop.

Only the last two lines of my code really matters to the problem.

My code:

<?php
ini_set('display_errors', 1); error_reporting(E_ALL);

ob_start();
session_start();
include 'connect.php';

$Listingid =($_POST['listingid']);

if(isset($_FILES['file'])) {
    $_FILES["file"]["name"] = preg_replace('/\s+/', '', $_FILES["file"]["name"]);
    for($i=0;$i<count($_FILES["file"]["name"]);$i++)
    {

        $photo=$_FILES["file"]["name"][$i];
        $newname=$Listingid.$photo;
        move_uploaded_file($_FILES["file"]["tmp_name"][$i], "photo/$Listingid$photo");

        mysqli_query($con,"INSERT INTO listingpic (pic,listingid) VALUES ('$newname','$Listingid');") or die(mysqli_error($con));

        $arr = array('picname' => $Listingid.$photo);
        echo json_encode($arr);
    }
}

Upvotes: 0

Views: 63

Answers (1)

giessebi
giessebi

Reputation: 168

$arr[]=array('picname' => $Listingid.$photo);

then move the echo json_encode out of the loop

Upvotes: 2

Related Questions