从Mysql中获取数据并转换为PHP数组 [英] Get data from Mysql and convert into PHP array
本文介绍了从Mysql中获取数据并转换为PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在一个我认为一定很简单的问题上得到一些帮助,但我已经被困了一段时间.
I hope to get some help on a problem that I suppose must be simple but I have been stuck for a while.
我有一个简单的 Mysql 表,其中包含 3 个字段(id、customer、sales).我只需要查询这个表并获得一个 php 数组.
I have a simple Mysql table with 3 fields ( id, customer, sales ) . All I need is to query this table and get an php array.
这是我的代码:
$query = "SELECT * FROM mysqltable";
$result = $mysqli->query($query))
我需要编写一个代码来循环并获取这种格式的数组:
I need to write a code to loop and get an array in this format:
$row=array(0=>"500,200",1=>"500,300",2=>"1000,600",3=>"800,400",4=>"200,500");
所以我可以以
echo json_encode($row);
非常感谢您帮助解决此问题.
Would appreciate any help to solve this.
推荐答案
可以使用mysqli_fetch_all()
You can use mysqli_fetch_all()
mixed mysqli_result::fetch_all ([ int $resulttype = MYSQLI_NUM ] )
或
mixed mysqli_fetch_all ( mysqli_result $result [, int $resulttype = MYSQLI_NUM ] )
参考阅读http://php.net/manual/en/mysqli-result.fetch-all.php
还有
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli->query($query);
while($row = $result->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
echo $row['CountryCode'];
}
/* free result set */
$result->close();
/* close connection */
$mysqli->close();
?>
这篇关于从Mysql中获取数据并转换为PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文