Return Json from php to jquery ui

3

I have a code in php that does a return of data in JSON. When it has only one value it returns as it should:

  

["[email protected]"]

When more than one value is found it returns as follows:

  

[ "[email protected]", "[email protected]",].

How do I return it this way?:

  

["[email protected]", "[email protected]"]

Below is the PHP script:

<?php
$lik = mysql_connect("localhost",'root','root');
$link = mysql_select_db('projeto4',$lik);

$search = $_GET['term'];
$qr = "SELECT nome,email FROM usuarios WHERE nome LIKE '%$search%' ORDER BY nome ASC";
$ex = mysql_query($qr) or die (mysql_error());

$resJson = '[';
$first = true;

while($res = mysql_fetch_array($ex)):
    if(!$first):
        $resJson .= ', ';
    else:
        $first = false;
    endif;
    $resJson .= json_encode($res['email']);
endwhile;

$resJson .= ']';

echo $resJson;
    
asked by anonymous 11.02.2016 / 11:42

2 answers

1

Transform your string $resJson into an array so $resJson = array();

Then you just increment the array with values like this:

array_push($resJson, $res['email']);

At the end you use json_encode($resJson);

Example on ideone

    
11.02.2016 / 12:06
1

The problem is that in your pack not all records should have e-mail thus generating content with vazio value. To rev it this problem you can do so:

$resJson = '[';
$first = true;

while($res = mysql_fetch_array($ex)):
    if(!empty($res['email'])){    // condição a mais
        if(!$first):
            $resJson .= ', ';
        else:
            $first = false;
        endif;
        $resJson .= json_encode($res['email']);
    }
endwhile;

$resJson .= ']';

Using the corigo that already has just adding one more condition.

Or do so:

$resJson = array();
while($res = mysql_fetch_array($ex)):
    if(!empty($res['email'])){
        $resJson[] = $res['email'];
    }
endwhile;

echo json_encode($resJson);

Or even so:

$resJson = array();
while($res = mysql_fetch_array($ex)):
    $resJson[] = $res['email'];
endwhile;

$resJson = array_filter($resJson, function($item){
    return !empty($item);
});

echo json_encode($resJson);

All of them are intended to remove the vazios values.

    
11.02.2016 / 12:29