PHP / MySql更改数组格式
问题描述:
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!
我有一个名为$ myArray的数组: p>
Array(
[0] => bb
[1] => kk
[2] => ll)
code> pre>
我在 查询: p>
$ sql =(“SELECT username FROM Users WHERE username IN('”。implode(“','”,$ myArray)。“')状态 > 0“);
$ result = $ conn-> query($ sql) - > fetchAll(PDO :: FETCH_ASSOC);
print_r($ result);
code> pre> \ n
我得到的是: p>
Array(
[0] => Array([username] => bb)
[1] =>数组([用户名] => kk))
code> pre>
但我想得到的是: p>
Array(
[0] => bb
[1] => kk))
code> pre>
我能做些什么来实现这个目标? p>
提前致谢! p>
div>
答
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'];
}
答
<?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);
?>
答
If you want a 1 liner:
$result = array_column($result,"username");