在PHP Mysql中创建json_encode

时间:2016-07-28 13:03:13

标签: php arrays json

我只想使用php从mysql结果创建一个json编码数据。我有一个员工详细信息表,我想从这些json_encoded数组中显示一个表数据。

{
  "data": [
    [
      "Tiger Nixon",
      "System Architect",
      "Edinburgh",
      "5421",
      "2011/04/25",
      "$320,800"
    ],
    [
      "Garrett Winters",
      "Accountant",
      "Tokyo",
      "8422",
      "2011/07/25",
      "$170,750"
    ]
]
}

我是json_encode的新手,我试过

$sql_sel = mysqli_query($con,"SELECT * FROM `table`");
$array = array();
$i = 0;
while($res_sel = mysqli_fetch_array($sql_sel)){
    $array['data'][$i] = $res_sel['name'];
    $i++;
}

$json_val = json_encode($array);
echo "<pre>";
print_r($json_val);

1 个答案:

答案 0 :(得分:0)

您需要使用mysqli_fetch_row()

$sql_sel = mysqli_query($con,"SELECT * FROM `table`");
$array = array();
while($res_sel = mysqli_fetch_row($sql_sel)){
    $array['data'][] = $res_sel;
}

否则,您不会在单独的子阵列中拥有数据集,但是 - 如您的示例中所示 - 只有name值。