Home > Net >  PHP can't convert array to JSON object in foreach loop
PHP can't convert array to JSON object in foreach loop

Time:08-26

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"}

Why there is no commas between them? and I don't think this is a JSON object

CodePudding user response:

Why there is no commas between them?

Because you didn't echo any.

and I don't think this is a JSON object

You are correct; it is a sequence of JSON objects next to each other, because that's what you asked PHP to produce.

In your loop, you are taking each array, and echoing it as JSON; but at no point are you joining those together in any way. If you want them all to be part of one JSON object at the end, you need to combine them first, and then run json_encode once. For example:

// 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);

CodePudding user response:

Your problem is when you store $data in $combined_data, you're doing it in the wrong way. use array_push() function instead, as I suggest:

$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);
  • Related