Json return from php to jquery ui

Asked

Viewed 58 times

3

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

["[email protected]"]

When more than one value is found returns as follows:

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

How do I make you come back 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;

2 answers

1

Transform your string $resJson in an array like this $resJson = array();

Then you will just increment the array with the values like this:

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

At the end you use the json_encode($resJson);

Example in ideone

1

The problem is that in your flock not all registrations should have email so generating content with value vazio. To solve 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 chord you already have 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 still :

$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);

They all aim to remove the values vazios.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.