Ask Your Question
2

How to use foreach to generate JSON in PHP?

asked 2023-05-26 17:45:23 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-26 17:56:01 +0000

lakamha gravatar image

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 }
]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-26 17:45:23 +0000

Seen: 12 times

Last updated: May 26 '23