【发布时间】:2016-06-12 11:14:53
【问题描述】:
我正在尝试回显一个由数组组成的 json 编码数组,但我不知道它不会让我打印那个东西。这是我的代码:
<?php
include_once('confi.php');
header('Content-type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$lastRecord = isset($_POST['lastRecordID']) ?
mysql_real_escape_string($_POST['lastRecordID']) : "";
$queryForTotalRec = mysql_query("SELECT customer_id FROM `WebServiceTesting`.`sapphire` ORDER BY customer_id DESC LIMIT 1");
$total_rec = mysql_fetch_row($queryForTotalRec);
if($total_rec){
$queryForAllRecords = "SELECT * FROM `WebServiceTesting`.`sapphire` WHERE customer_ID BETWEEN %d AND %d";
$get_all_recs = mysql_query(sprintf($queryForAllRecords, $lastRecord, $total_rec[0]));
$json = array();
while($row = mysql_fetch_assoc($get_all_recs)){
$json[] = array("Status" => 1, "NewRecord" => $row);
}
print_r($json);
echo json_encode($json);
}else{
$json = array("status" => 0, "Error_Message" => mysql_error());
echo json_encode($json);
}
}else{
$json = array("status" => 0, "Error_Message" => "Request Method not correct");
echo json_encode($json);
}
@mysql_close($conn);
错误: 格式错误的 JSON:意外的“A”有时是“I”
当我删除 print_r 行时,我得到: 未收到回复 当我打印 $json 数组的计数时,我得到了 153 的计数,但没有其他输出。
我尝试过的事情:
我阅读了一些类似问题的解决方案,您需要使用 array_values() 例如:
echo json_encode(array_values($json));
相同的响应:'未收到响应'
我也尝试将 echo $json 放入循环中,我知道这在概念上是错误的,但仍然得到预期的错误“语法错误”
另外,我尝试通过 foreach 回显没有运气语法错误,但我可以看到原始输出但无法验证 json。
仅针对 print_r 的信息,这是响应:
Array (
[0] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1241
[firstName] => Katy
[lastName] => Lest
[email] => klest@yahoo.com [phone] => 787012425
)
)
[1] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1242
[firstName] => Hanah
[lastName] => Morrisn
[email] => road@gmail.com
[phone] => 144221275 )
)
[2] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1243
[firstName] => James
[lastName] => McGrath
[email] => rosamcgrath@hotmail.com
[phone] => 79684312 )
)
)
刚刚找到了一个答案,如果有人可以提供帮助,我仍在寻找一个理由。我提取的记录数量为 150 多条,所以我一次只尝试了 50 条记录,而且效果很好。任何人都知道我如何才能真正为我的数组分配更多内存,以便它可以一次保存所有需要的数据?
我也尝试过给出准确的索引,我认为数组内存不足,但这甚至不起作用:
$json = new SplFixedArray($difference);
非常感谢您的帮助。
【问题讨论】:
-
在
echo之后尝试exit。 -
运气不好,同样的错误'没有收到响应'。
-
注意:
mysql_*函数已被弃用,它们已从 PHP 7 中删除,当您升级到该版本时,您的代码将停止工作。您不应该使用它们编写新代码,而是使用mysqli_*or PDO。 -
@GeraldSchneider 确定我会的,实际上我在很长一段时间后都在研究 php,即使那时我还是初学者,所以只是因为熟悉语法,我正在这样做。
标签: php mysql arrays json memory