Mysql PDO array with Json error in view

Asked

Viewed 87 times

1

I’m having a hard time with json_encode

echo json_encode($autocomplete -> fetchAll(PDO :: FETCH_ASSOC));

i am doing a database select so far so all right, but when it transfers the data to this echo up there, appear many characters that javascript is not accepting, as I transform the output from above that is displayed as below

[{"user_name":"Roberto Monteiro"},{"user_name":"Dk Teclive"},{"user_name":"Fye Flourigh"}]

in the format below that is accepted by javascript

["Roberto Monteiro", "Dk Teclive", "Fye Flourigh"];

I mean, how can I turn this

[{"user_name":"Roberto Monteiro"},{"user_name":"Dk Teclive"},{"user_name":"Fye Flourigh"}]

and leave in this format

["Roberto Monteiro", "Dk Teclive", "Fye Flourigh"];

whether with php or javascript, if possible, in both ways, thanks from now on.

2 answers

1


In your javascript the first step is parsing the string sent by php in a valid json, then you can access the array like this: lista[i].user_name or lista[i]['user_name'] or you can still use jquery to make lista a simple array(it is also possible to do with pure javascript).

var lista = JSON.parse('[{"user_name":"Roberto Monteiro"},{"user_name":"Dk Teclive"},{"user_name":"Fye Flourigh"}]');
var array_simples = $.map(lista, function (item) {
        return item.user_name;
    });
  • Dude, you’re a genius, it worked 100%, thank you very much.

0

Maybe using array_values:

echo json_encode($autocomplete -> array_values(fetchAll(PDO :: FETCH_ASSOC)));

  • Look, when I put it there, my whole page went blank, rsrs, it got really bad, can you help me with this? http://answall.com/questions/43291/pesquisa-din%C3%A2mica-com-json-php-mysql

Browser other questions tagged

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