S
S
skyfly20102016-09-22 16:49:34
PHP
skyfly2010, 2016-09-22 16:49:34

how to create json string in php

Good afternoon. I decided to study json for general development. Faced with the fact that I can not create the correct json string on my own. =( I found an article on the Rusler, in which the following example was given:

<?php
$cart = array(
  "orderID" => 12345,
  "shopperName" => "Ваня Иванов",
  "shopperEmail" => "[email protected]",
  "contents" => array(
    array(
      "productID" => 34,
      "productName" => "Супер товар",
      "quantity" => 1
    ),
    array(
      "productID" => 56,
      "productName" => "Чудо товар",
      "quantity" => 3
    )
  ),
  "orderCompleted" => true
);
 
echo json_encode( $cart );
?>

Let's say he gets a string here. And how to make it so that you can set 50, 100, 1000 products, for example, in a cycle.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Kostyuk, 2016-09-22
@skyfly2010

Make an object (an array of arrays). It doesn't matter how many arrays there are. Use json.parser.online.fr to parse and view results.

$test = array();

foreach($products as $product){
    $test[] = array(
        "id"=>$product->id,
        "title"=>$product->title,
        "param"=>array(
            "param1"=>21,
            "param2"=>2,
        ),
    );
}

echo json_encode($test);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question