В приведенном ниже коде представлено множество изображений. У меня есть 15 полей: "img1", "img2", "img3" и т.д.
Иногда не все поля имеют данные. Я не хочу включать их в массив. Есть ли способ сохранить эти пустые поля вне массива?
<?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);
?>
Вам нужно нормализовать свои данные вместо полей с именами, такими как img15
. Поместите изображения в другую таблицу со ссылкой на imovel_id
. Нормализованные данные сделают это намного проще.
С вашей текущей структурой таблицы у вас нет выбора, кроме как делать много и много операторов if
(или цикл над данными). Что-то вроде этого:
<?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);
?>
Просто измените свой массив-наполнитель с помощью оператора IF:
if($row['img1']) $images[] = array('images' => $row['img1'];
Поэтому он добавит только тот, если в нем что-то есть.