生成PHP阵列对JS
问题描述:
表使用方法:生成PHP阵列对JS
--------------------
Product | Price
--------------------
apples | 5
oranges | 6
peaches | 7
如何从表中获取行,并生成一个JSON阵列?
答
喜只需fetch
从数据table
并使用json_encode
$con = mysqli_connect('localhost','root','password','yourdatabase') or die("Could not connect database");
$result = mysqli_query($con,"select * from youtable");
$arr = array();
while($row = mysqli_fetch_assoc($result)){
$arr['myproducts'][] = $row;
}
$js_array = json_encode($arr);
echo $js_array;
?>
输出
{"myproducts":[{"price":"4","products":"apples"},{"price":"5","products":"oranges"}]}
答
你应该简单只是做SQL SELECT
,然后它的结果应该是json_encode()
例子:
SELECT * FROM `table_name`
Afther这在你的代码:
while($r = $result->fetch_assoc()) {
$newArr[] = $r;
}
echo json_encode($newArr);
http://stackoverflow.com/help/how-to-ask。 –
什么是'js数组'? – Saty
所以你想让我们为你写一切吗?从MySQL查询 - > PHP - >达到JavaScript? –