[英]PHP can't convert array to JSON object in foreach loop
I want to parse this JSON Object later in C# but can't convert the array in the foreach loop to the correct format for JSON Object.
$data = [];
$servers = $srv->getAllSrv();
foreach ($servers as $server) {
$server->status();
$ip_port = $server->addr() . ':' . $server->port();
$hostname = $server->hostname();
$data["hostname"] = $hostname;
$data["ip_port"] = $ip_port;
$data_json = json_encode($data, JSON_FORCE_OBJECT);
echo $data_json;
}
// output:
{"hostname":"Server 1","ip_port":"1.1.1.1:1"}{"hostname":"Server 2","ip_port":"1.1.1.1:1"}{"hostname":"Server 3","ip_port":"1.1.1.1:1"}{"hostname":"Server 4","ip_port":"1.1.1.1:1"}{"hostname":"Server 5","ip_port":"1.1.1.1:1"}
为什么它们之间没有逗号? 我不认为这是 JSON object
为什么它们之间没有逗号?
因为你没有回应。
我不认为这是 JSON object
你是对的; 它是一系列相邻的 JSON 对象,因为这是您要求 PHP 生成的。
在您的循环中,您正在获取每个数组,并将其回显为 JSON; 但是您绝不会以任何方式将它们结合在一起。 如果您希望它们全部成为 JSON object 最后的一部分,则需要先将它们组合起来,然后运行json_encode
一次。 例如:
// start with an empty structure to add things to
$combined_data = [];
foreach ($servers as $server) {
// your code to build the item here
$data = ...
// add the item to the combined structure; in this case, adding it to a list
$combined_data[] = $data;
// Note: no echo here!
}
// output the whole thing as one JSON string; in this case, a JSON array
echo json_encode($combined_data);
您的问题是当您将 $data 存储在 $combined_data 中时,您以错误的方式进行操作。 正如我建议的那样,请use array_push()
function :
$combined_data = [];
$servers = $srv->getAllSrv();
foreach ($servers as $server) {
$server->status();
$ip_port = $server->addr() . ':' . $server->port();
$hostname = $server->hostname();
$data["hostname"] = $hostname;
$data["ip_port"] = $ip_port;
// don't do it in this way => $combined_data[] = $data;
// do this instead
array_push($combined_data, $data);
//this will solve your problem
}
echo json_encode($combined_data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.