我有以下问题,我的php代码从dB获取所需的数据:
import numpy
import pandas
import networkx as nx
import unicodecsv as csv
path="comics-network.csv"
graph = nx.Graph(name="Characters in Comics")
with open(path, 'rb') as data:
reader = csv.reader(data)
for row in reader:
if 'nodedef' in row[0]:
handler = lambda row,G: G.add_node(row[0],TYPE=row[1])
elif 'edgedef' in row[0]:
handler = lambda row,G: G.add_edge(*row)
else:
handler=(row, graph)
如您所见,这写入json文件 - 结果:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
当我使用以下js代码从json文件中提取时:
{"0":{"nmech":"2.00","nelect":"2.00","nplant":"2.00","ncivil":"2.00"}}
使用chrome的控制台日志显示以下内容:
$.getJSON('newport.json', function(data) {
console.log(data);
仅显示第一个键/值对而不是所有4个K / V对?有人可以解释我做错了吗。
答案 0 :(得分:1)
将结果写入json文件是过度的,恕我直言。为什么不将json添加到模板或页面视图(PHP)中。
SELECT Gate, Category, SUM("Delay Minutes") AS "Delay Minutes"
FROM
(
SELECT Gate AS Gate,
Dly1Cat AS Category,
DLY1Min AS "Delay Minutes"
FROM YourTable
UNION ALL
SELECT Gate AS Gate,
Dly2Cat AS Category,
DLY2MIN AS "Delay Minutes"
FROM YourTable
UNION ALL
SELECT Gate AS Gate,
Dly3Cat AS Category,
DLY3MIN AS "Delay Minutes"
FROM YourTable
)
WHERE Category IS NOT NULL
GROUP BY Gate, Category;
显然,您没有注册名称空间对象,但这只是在首次加载页面时从PHP设置设置的示例方法。
你真的需要输出一些数据。
<script>
// Create settings from PHP/Session and
// Initialize Registration Namespace
var registrationSettings = <?php echo (!empty($data)) ? @json_encode($data) : json_encode(array()); ?>;
Registration.init({ settings: window.registrationSettings });
</script>
也许更简单的写作方式就是。
<script>
var newport = <?php echo (!empty($emparray)) ? @json_encode($emparray) : json_encode(array()); ?>;
</script>
我可以看到您尝试归档(或缓存)结果。您可能应该在PHP控制器中编写一个AJAX方法来处理请求。数据可以在Memcached中缓存服务器端或其他一些快速数据处理程序。大多数PHP框架都支持memcached。
答案 1 :(得分:0)
这没关系,因为你的PHP数组看起来像这样:
<?php
$arr = [
[
"key1" => "value1",
"key2" => "value2",
]
]
您必须使用数据[0] [&#39; key&#39;]访问第一个元素的key1部分。
另一个(更好的解决方案)是不要在php中使用while循环,因为你期望在你的情况下从mysql返回1个元素。这样使用:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
//Get first row from db.
$emparray = mysqli_fetch_assoc($result);
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
现在,您的数据将以javascript的形式开始。