1 | initial version |
Here is an example of using foreach loop to generate JSON in PHP:
Suppose you have an array of objects (e.g. products) that you want to convert to JSON:
$products = array(
array("id" => 1, "name" => "Product 1", "price" => 10.99),
array("id" => 2, "name" => "Product 2", "price" => 15.99),
array("id" => 3, "name" => "Product 3", "price" => 9.99)
);
To convert this array to JSON using foreach loop, you can do the following:
$json = "[";
foreach ($products as $product) {
$json .= '{ "id": ' . $product["id"] . ', "name": "' . $product["name"] . '", "price": ' . $product["price"] . ' },';
}
$json = rtrim($json,","); // remove the last comma
$json .= "]";
echo $json;
This code will output the following JSON:
[
{ "id": 1, "name": "Product 1", "price": 10.99 },
{ "id": 2, "name": "Product 2", "price": 15.99 },
{ "id": 3, "name": "Product 3", "price": 9.99 }
]