生成用于js的php数组

时间:2016-08-17 07:54:37

标签: javascript php arrays

表:

node -pe 'require("dns").lookup("ya.ru",function(){console.dir(arguments)})'     
GetAddrInfoReqWrap {
  callback: { [Function: asyncCallback] immediately: true },
  family: 0,
  hostname: 'ya.ru',
  oncomplete: [Function: onlookup] }
 { '0': null, '1': '213.180.193.3', '2': 4 }

如何从表中获取行并生成json数组?

2 个答案:

答案 0 :(得分:1)

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

示例:

SELECT * FROM `table_name`

在你的代码中有这个:

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

echo json_encode($newArr);

答案 1 :(得分:0)

来自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"}]}