Selim Selim - 5 months ago 12
JSON Question

Autocomplete json_encode return by column

I'm using the autocomplete UI for my search box. Below is my php code:

<?php
include 'connect.php';

if (isset($_GET['term'])) {
$value = $_GET['term'] . '%';
$return_arr = array();

$stmt = $conn->prepare("SELECT * FROM jobs WHERE jobname LIKE ? or formtype LIKE ?");
$stmt->bind_param("ss", $value, $value);
$stmt->execute();
$stmt->bind_result($entryid, $jobnumber, $jobname, $formtype, $date);

while ($stmt->fetch()) {
$return_arr[] = $jobname;
$return_arr[] = $formtype;
}

echo json_encode($return_arr);

}
?>


Everything works perfectly fine. But I kind of want for the while statement to return all
$jobname
values first before the
$formtype
values. In short, I want the values to be returned by column and not by row. I'm not sure how it is possible because I tried putting them inside do while and foreach statements but both didn't work for me.

Also for some reason, when I create another echo statement, the:

echo json_encode($return_arr);


stops working.

Answer

. But I kind of want for the while statement to return all $jobname values first before the $formtype values.

Build two arrays and then merge them:

$ar1 = [];
$ar2 = [];
while($stmt->fetch()) {

$arr1[] =  $jobname;
$arr2[] =  $formtype;

  }
$return_arr = array_merge($arr1, $arr2);

Also for some reason, when I create another echo statement, the: echo json_encode($return_arr); stops working.

Because autocomplete expects json object and you want to try give him json object and something else