Corey Hart
Corey Hart

Reputation: 193

PHP/MySql changing format of array

I have this array named $myArray:

Array ( 
[0] => bb 
[1] => kk
[2] => ll ) 

On which I´m querying with:

$sql = ("SELECT username FROM Users WHERE username IN ('" .   implode("','",$myArray) . "')   AND status > 0 ");
$result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
print_r ($result);

What I get is:

Array ( 
[0] => Array ( [username] => bb ) 
[1] => Array ( [username] => kk ) )

But what I want to get is:

Array ( 
[0] => bb 
[1] => kk ) )

What can I do to achieve this?

Thanks in advance!

Upvotes: 0

Views: 31

Answers (3)

apokryfos
apokryfos

Reputation: 40653

If you want a 1 liner:

$result = array_column($result,"username"); 

Upvotes: 0

Rushil K. Pachchigar
Rushil K. Pachchigar

Reputation: 1321

<?php 
$query =  $conn->prepare("SELECT username FROM Users WHERE username IN ('" .   implode("','",$myArray) . "')   AND status > 0 ");
$query->execute();
$myArray = array();
if($query->rowCount() > 0){
    $i = 0;
    while($data = $query->fetch(PDO::FETCH_ASSOC) ){
        //echo "<pre>";print_r($data);echo"</pre>";
        $myArray[$i] = $data;
        $i++;
    }
}
print_r($myArray);
?>

Upvotes: 2

Haotian Liu
Haotian Liu

Reputation: 886

The printed array is in the format in which it should be.

This is because that you may select more than one column in an SQL query, so that each row should be an array.

What you can do is simply traverse the array again and re-format the array to the shape you want.

foreach ($result as &$value){
    $value = $value['username'];
}

Upvotes: 1

Related Questions