Necro.
Necro.

Reputation: 987

Unify Array For JSON Encode?

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

Upvotes: 0

Views: 200

Answers (3)

Alix Axel
Alix Axel

Reputation: 154543

$players = array
(
    'name' => iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($players)), false),
);

Demo.


With PHP 5.5, you also have array_column().

Upvotes: -1

Kevin Vaughan
Kevin Vaughan

Reputation: 15180

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).

Upvotes: 2

raina77ow
raina77ow

Reputation: 106385

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

Upvotes: 1

Related Questions