生成PHP阵列对JS

生成PHP阵列对JS

问题描述:

表使用方法:生成PHP阵列对JS

-------------------- 
Product | Price 
-------------------- 
apples | 5 
oranges | 6 
peaches | 7 

如何从表中获取行,并生成一个JSON阵列?

+1

http://stackoverflow.com/help/how-to-ask。 –

+1

什么是'js数组'? – Saty

+0

所以你想让我们为你写一切吗?从MySQL查询 - > PHP - >达到JavaScript? –

喜只需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"}]} 
+0

非常感谢,它的作品! – Razvan

+0

@Razvan如果它的作品请标记它你的回答:) – user1234

你应该简单只是做SQL SELECT,然后它的结果应该是json_encode()

例子:

SELECT * FROM `table_name` 

Afther这在你的代码:

while($r = $result->fetch_assoc()) { 
$newArr[] = $r; 
} 

echo json_encode($newArr);