将php数组转换为js selectpicker数组格式

时间:2017-04-04 15:14:54

标签: javascript php mysqli

这是我构建sql数据并发送回ajax调用的方式:

    (...)
    $sql = "SELECT id_option FROM options WHERE id_win = '{$id_win}'";
    $result = mysqli_query($conn, $sql);
    $rows =  array();
    while ($row = mysqli_fetch_array($result)) {
      $rows[] =  $row;
    }

    $data["win_data"] = $rows;
    echo json_encode($data);

这是我的ajax函数,用于从DB获取selectpicker的选项:

$.ajax({
  type: "POST",
  url: ...,
  data: ...,
  dataType: "json",
  success: function(data)   {       
    $("#id_win").selectpicker("val", data.win_data);
   // $("#id_win").selectpicker("val", [1,3];
  }
});

data.win_data变量应为:[1,3]

但如果我这样做: 的console.log(JSON.stringify(data.win_data)); 我明白了:

[{"0":"1","id_option":"1"},{"0":"3","id_option":"3"}]

为selectpicker获取正确格式数组的最简单方法是什么?

2 个答案:

答案 0 :(得分:2)

这是因为$row是一个数组。看:https://secure.php.net/manual/pt_BR/mysqli-result.fetch-array.php

你必须这样使用:

    (...)
    $sql = "SELECT id_option FROM options WHERE id_win = '{$id_win}'";
    $result = mysqli_query($conn, $sql);
    $rows =  array();
    while ($row = mysqli_fetch_array($result)) {
      $rows[] =  $row['id_option'];
    }

    $data["win_data"] = $rows;
    echo json_encode($data);

答案 1 :(得分:1)

忘记了mysqli并使用PDO,它有everything you need

$stmt = $pdo->prepare("SELECT id_option FROM options WHERE id_win = ?");
$stmt->execute([$id_win]);
$data["win_data"] = $stmt->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($data);

此代码是更短 2倍安全