使用PHP输出数组

时间:2016-03-08 13:04:15

标签: php mysql

我有以下PHP代码:

var _eventAggregator = Substitute.For<IEventAggregator>();

我在数据库中获取列名为“name”的所有数据。我怎么能这样输出呢?

 while($row = mysqli_fetch_array($query))
 {
    $data = $row['name'];
 }

4 个答案:

答案 0 :(得分:6)

你必须将$ data作为数组类型变量。

 while($row = mysqli_fetch_array($query))
 {
   $data[] = $row['name'];
 }

 print_r($data); // required output

答案 1 :(得分:4)

 while($row = mysqli_fetch_array($query))
 {
   $data[] = $row['name'];
 }

 print_r($data); // output key wise display like
 Array ( [0] => John [1] => Doe  ) etc.

但按照您的建议输出然后只需添加json_encode()

print_r(json_encode($data)); // output like
["John", "Doe", "Deer"]

答案 2 :(得分:3)

$data = [];
while($row = mysqli_fetch_array($query))
{
  $data = $row['name'];
}
echo json_encode($data); // or you can use print_r for debugging.

答案 3 :(得分:1)

您需要在数组中使用json_encode()方法在jquery中接受。重新排列代码如下......

$data = array();
while($row = mysqli_fetch_array($query))
{
   $data[] = $row['name'];
}

$new_array = json_encode($data);
echo $new_array;   // use 'echo' to print. The json_encode() convert $data array to string.