【问题标题】:Converting list of values from MySQL into array with square brackets将 MySQL 中的值列表转换为带方括号的数组
【发布时间】:2021-07-12 03:07:58
【问题描述】:

我想用来自 MySQL 数据的 ApexCharts 显示一个图表。

我正在通过 axios 和一个带有与数据库通信的函数的 php 文件连接到我的数据库。一个典型的 vue 方法是这样的:

myfunction: function(){
  axios.post('ajaxfile.php', {
    request: 1,
  })
  .then(function (response) {
    alert(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
  },

在 ajaxfile.php 中,这个请求像这样继续,并以 json 编码回显:

if($request == 1){
$data = mysqli_query($con,"SELECT * from mytable");

  $result = array();
  while($row = mysqli_fetch_assoc($data)){
    $result[]=$row;
  }
  echo json_encode($result);
  exit;
}

ApexCharts 像这样在 vue.js 的数据部分中提取数据,这(在本例中)是具有 30% 和 70% 数据的饼图的基础:

data: {
    chartdata: [30, 70],
}

我想要实现的是从我的 ajaxfile.php 中的数据库中选择两个数值并从中创建一个饼图。所以像:

if($request == 1){
$data1 = mysqli_query($con,"SELECT * from mytable WHERE id=1");
  $result1 = mysqli_fetch_assoc($data1);

$data2 = mysqli_query($con,"SELECT * from mytable WHERE id=2");
  $result2 = mysqli_fetch_assoc($data2);

 $chartdata = $result1.','.$result2;

  echo json_encode($chartdata);
  exit;
}

在 Vue.js 中:

  myfunction: function(){
      axios.post('ajaxfile.php', {
        request: 1,
      })
      .then(function (response) {
        app.chartdata = response.data;
      })
      .catch(function (error) {
        console.log(error);
      });
      },

我的 ajaxfile 中的图表数据应该保存在 vue 的 app.chartdata 中,以便 ApexCharts 可以从中构建图表。

但是我怎样才能实现需要的格式呢?

[30,70]

我几乎尝试了一切。即使用额外的括号重建格式也无济于事。喜欢:

app.chartdata ="[ "+app.chartdata +" ]";

【问题讨论】:

    标签: php mysql json vue.js axios


    【解决方案1】:

    在 javascript 中可以做到这一点,下面是在 MySQL 中做到这一点的方法。

    当select * from mytable 产生时:

    id
    30
    70

    你可以select group_concat(id) as id from mytable,得到:

    id
    30,70

    甚至:

    select concat('[',group_concat(id),']') as id from mytable
    

    然后得到:

    id
    [30,70]

    【讨论】:

    • 这行得通!我认为尝试在 javascript 中转换内容可能存在问题。直接在 mysql 中执行此操作的方法非常有效!谢谢!
    猜你喜欢
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多