0

I'm trying to json_encode my array I'm getting back so I can place it inside of a jQuery plugin for the data source. My issue is that I am using PDO to query my database to get back the array, but upon doing a print_r, I see that every name I'm getting back from my database is in its own array. How would I place all these results into a single array so that when I do my json_encode it is all in one readable string for the jQuery plugin?

Database Query (PDO) -

$query = "
           SELECT name
FROM  `clients` 
    ";      
    try 
    {
        $stmt = $b3->prepare($query); 
        $stmt->execute(); 
    } 
    catch(PDOException $ex) 
    {  
        die("Failed to run query: " . $ex->getMessage()); 
    } 
    $players = $stmt->fetchAll();

Example of the returned array upon doing (Note I have 8000 getting returned so I will only post the first 5 or so)

print_r($players);

 Array
( 

 [0] => Array
        (
            [name] => ! CBC.ZXR
    )

[1] => Array
    (
        [name] => ! marioxz
    )

[2] => Array
    (
        [name] => ! V v :]
    )

[3] => Array
    (
        [name] => !?!
    )

[4] => Array
    (
        [name] => !CU @ 1337
    )

So more or less, how would I unify my array, so that when I do

json_encode($players["name"]);

It will return back a single JSON string of the names mentioned above.

Edit

Current Code,

$query = "
       SELECT name
FROM  `clients` 
";      
try 
{
    $stmt = $b3->prepare($query); 
    $stmt->execute(); 
} 
catch(PDOException $ex) 
{  
    die("Failed to run query: " . $ex->getMessage()); 
} 
$playerNames = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

json_encode($playerNames);
var_dump(json_last_error());
7
  • json_encode returns a value, it doesn't transform its argument. Store this value ($playerNamesJson = json_encode($playerNames);) and/or echo it. Right now you're just throwing the result away. Commented May 31, 2013 at 0:40
  • @raina77ow I have done this, but that doesn't look like a normal JSON string to me. gophobia.com/beta/ajaxSearch.php Commented May 31, 2013 at 0:44
  • 1
    And yet it is, obviously. Check the source, not the page as shown to you. Check its contents with json validator. Commented May 31, 2013 at 0:46
  • ... and as a sidenote: are you sure you need the whole set of results transferred to the front-end? For autocomplete needs, usually only a small subset (which matches the pattern) is returned. Commented May 31, 2013 at 0:49
  • I'm using Bootstrap Typeahead, and as of now, with that string that we got by doing your first comment, whenever I enter a single key, it loops that key entered, and then when I enter more then one key, it returns nothing. I'm not sure how to debug this... Commented May 31, 2013 at 0:51

3 Answers 3

2

If you are trying to just get a single level array with the first column of results from your database query, consider passing in the fetch type to your fetchAll call:

$playerNames = $sth->fetchAll(PDO::FETCH_COLUMN, 0);

This should result in $playerNames being an array of the format you are looking for, which you can pass to json_encode or whatever else you would like. For more information on fetch options, you can see the examples in the php docs (http://php.net/manual/en/pdostatement.fetchall.php).

Sign up to request clarification or add additional context in comments.

10 Comments

when I do json_encode, it isn't returning anything. gophobia.com/beta/ajaxSearch.php will show what I'm getting back. It's a rather large array.
@AlixAxel Warning: json_last_error() expects exactly 0 parameters, 1 given
What is your call to json_encode? It sounds like the problem with what you are doing might be in there since you now have back the array in the format you desired.
@Necro.: I could repeat what PHP said but... json_encode($players); var_dump(json_last_error());
Based on your comments and the response returned from the link you posted, it looks like this answer worked for you to address this question. The best way to make use of stackoverflow would be to mark the answer that helped you as accepted, and then search for existing questions that help with the next problems you encounter. If you can't find any existing questions, then you could open a new one on that subject. Following these best practices will make it more likely that your future questions will be answered.
|
1

Well, you can use array_map on the resulting array of rows to create an array of names, like this:

$player_names = array_map(function($p) { return $p['name']; }, $players);

1 Comment

Check this demo, it does work - unless you're using PHP 5.2 (in which case there should be an error shown, as anonymous function is used).
-1
$players = array
(
    'name' => iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($players)), false),
);

Demo.


With PHP 5.5, you also have array_column().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.