madsongr
madsongr

Reputation: 785

PHP + json: do not include empty fields

The code below brings me an array of images. I have 15 fields: "img1", "img2", "img3" and so on.

Sometimes not all the fields have data. I don´t want to include them into the array. Is there a way to keep these empty fields outside the array?

<?php

include_once 'db_connect.php';

$i_id = $_POST["imovel_id"];

$sql = "SELECT * FROM iMoveis WHERE imovel_id='$i_id'";
$result = mysqli_query($mysqli, $sql);

$response = array();
$images = array();

while($row = mysqli_fetch_assoc($result)){

$images[] = array('images' => $row['img1']);
$images[] = array('images' => $row['img2']);
$images[] = array('images' => $row['img3']);
$images[] = array('images' => $row['img4']);
$images[] = array('images' => $row['img5']);
$images[] = array('images' => $row['img6']);
$images[] = array('images' => $row['img7']);
$images[] = array('images' => $row['img8']);
$images[] = array('images' => $row['img9']);
$images[] = array('images' => $row['img10']);
$images[] = array('images' => $row['img11']);
$images[] = array('images' => $row['img12']);
$images[] = array('images' => $row['img13']);
$images[] = array('images' => $row['img14']);
$images[] = array('images' => $row['img15']);

} 

  $response['posts'] = $images;

  echo json_encode($response, JSON_UNESCAPED_SLASHES);


?>

Upvotes: 1

Views: 78

Answers (2)

elixenide
elixenide

Reputation: 44841

Big Picture

You need to normalize your data instead of having fields with names like img15. Put the images in a different table with a reference to imovel_id. Normalized data would make this much easier.

Hacky Fix for Your Problem

With your current table structure, you have no choice but to do lots and lots of if statements (or a loop over the data). Something like this:

<?php

include_once 'db_connect.php';

$i_id = $_POST["imovel_id"];

$sql = "SELECT * FROM iMoveis WHERE imovel_id='$i_id'";
$result = mysqli_query($mysqli, $sql);

$response = array();
$images = array();

while($row = mysqli_fetch_assoc($result)){
    for ($index = 1; $index <= 15; $index++) { // loop over the columns
        if (!empty($row['img' . $index])) { // check for null or empty columns
            $images[] = array('images' => $row['img' . $index]); // add only if there is data
        }
    }
}
$response['posts'] = $images;
echo json_encode($response, JSON_UNESCAPED_SLASHES);
?>

Upvotes: 3

durbnpoisn
durbnpoisn

Reputation: 4669

Just modify your array populator with an IF statement:

if($row['img1'])  $images[] = array('images' => $row['img1'];

So it will only add that one if there is something in it.

Upvotes: 1

Related Questions