Create JSON data with PHP

Requirement:

You must have good knowledge about assosiative array in PHP

Briefing:

In this tutorial we will make:

  • One Object JSON
  • Several Objects inside One Array
  • One Object with One Children Array
  • One Object with Array of Array

Create One Object JSON

Create a dataJson.php filename and insert this code:

<?php

$sayur = array("Wortel" => 1000, "Bayam" => 2000, "Kangkung" => 3000, "Toge" => 15000);

echo json_encode($sayur);

?>

Result:

{“Wortel”:1000,”Bayam”:2000,”Kangkung”:3000,”Toge”:15000}

Create Several Objects inside One Array

Create a dataSeveral.php filename and insert this code:

<?php

$makanan = array ( 
      
    array( 
        "name" => "Somay", 
        "value" => "3000"
    ), 
    array( 
        "name" => "Pisang Goreng", 
        "age" => "1000"
	)
  
); 
  
echo json_encode($makanan); 
  
?> 

Result:

[{“name”:”Somay”,”value”:”3000″},{“name”:”Pisang Goreng”,”age”:”1000″}]

One Object with One Children Array

Create a dataJsonArray.php and insert this code:

<?php
 $makanan = array("makanan" => array ( 
   array( 
        "name" => "Somay", 
        "value" => "3000"
    ), 
    array( 
        "name" => "Pisang Goreng", 
        "age" => "1000"
		)
  )
); 
 echo "<pre>". json_encode($makanan,  JSON_PRETTY_PRINT)."</pre>";	
  
?> 

Result:

{
    "makanan": [
        {
            "name": "Somay",
            "value": "3000"
        },
        {
            "name": "Pisang Goreng",
            "age": "1000"
        }
    ]
}

One Object with Array of Array

Create a dataArrayOfArray.php and insert this code:

<?php
$makanan = array("makanan" => "Gado-gado", 
	   "beli" => array ( 
	               array( "name" => "Wortel", 
	                      "value" => "3000"
		            ), 
		      array("name" => "Tahu", 
			    "value" => "1000"
			   ),
		      array("name"=> "Bumbu",
			    "beli" => array(array("name" => "cabe", 
						"value" => 1000
							
						), array("name" => "kacang", 
						"value" => 3000
							
						))
							
					)
				
			)
);
 
echo "<pre>". json_encode($makanan,  JSON_PRETTY_PRINT)."</pre>";	
  
?> 

Result:

{
    "makanan": "Gado-gado",
    "beli": [
        {
            "name": "Wortel",
            "value": "3000"
        },
        {
            "name": "Tahu",
            "value": "1000"
        },
        {
            "name": "Bumbu",
            "beli": [
                {
                    "name": "cabe",
                    "value": 1000
                },
                {
                    "name": "kacang",
                    "value": 3000
                }
            ]
        }
    ]
}

Thanks for reading

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *