【发布时间】:2016-11-27 13:39:07
【问题描述】:
首先,我有以下 MySQL 表名作为 store_items :
id ref store item qty sell
1 2 m1 001 1 12.00
2 2 m1 002 3 12.00
3 3 m3 004 4 5.00
4 3 m3 003 8 10.00
并从一个简单的 PHP 代码开始将上述行转换为数组
<?php
$query = "SELECT * FROM store_items ORDER by store Asc";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
//This is for moving PHP array to JS array ? Not sure if it is correct
$js_arr = json_encode($data);
?>
现在我一直在寻找一种方法,而不是将其显示为表格,所以我想将这些结果放在一个看起来相似的 Excel 中,所以我找到了这个插件,名为:Javascript Handsontable
在放置样式表和脚本之后继续:
<script src="http://localhost/handsontable-master/dist/handsontable.full.js"></script>
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/dist/handsontable.full.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<style type="text/css">
body {background: white; margin: auto;}
h2 {margin: 20px 0;}
</style>
<div id="example" class="handsontable htColumnHeaders"></div>
所以问题出现在这里:
<script>
var array_code = '<?php echo $js_arr; ?>';
//Alerting result to make sure its correct
alert(array_code);
$(document).ready(function () {
//Not sure how to display the results here ???
var
data =
[
array_code
],
container = document.getElementById('example'),
hot;
hot = new Handsontable(container, {
data: data,
minSpareRows: 1,
colHeaders: true,
contextMenu: true
});
function bindDumpButton() {
Handsontable.Dom.addEvent(document.body, 'click', function (e) {
var element = e.target || e.srcElement;
if (element.nodeName == "BUTTON" && element.name == 'dump') {
var name = element.getAttribute('data-dump');
var instance = element.getAttribute('data-instance');
var hot = window[instance];
console.log('data of ' + name, hot.getData());
}
});
}
bindDumpButton();
});
但我无法实现正确的显示;我的目标是这样的:
但是当var data数组值是这样的时候上图显示正确
var
data = [
['1', '2', 'm1', '001', '1', '12.00'],
['2', '2', 'm1', '002', '3', '12.00'],
['3', '3', 'm3', '004', '4', '5.00'],
],
如何正确地将 PHP 数组值放入 JS 数组中?
任何建议将不胜感激。
【问题讨论】:
-
$js_arr = json_encode($data) 会产生 JSON 格式的数据。
-
@Perumal93 对不起,我在这里遗漏了什么,是否正确?
-
您想将数据数组直接放入表格中并显示出来?
-
是的,我已经尽力了,但我现在所取得的成就是整个数组 [0] 值都放在一个单元格 A 中,而不是每个单元格中的每个值都像图片一样以上。
-
如果是这样,那你就让它变得复杂了。我会在答案部分解释它们。
标签: javascript php mysql loops