PHP Array To Json Example


Share:
Published By: Admin, Published On: May 07, 2021, Category: PHP

Hi Dev,

In this blog, I will learn you How to create an array for JSON using PHP.

The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.

Syntax :
string json_encode( $value, $option, $depth )

Parameters :

  • $value:It is a mandatory parameter which defines the value to be encoded.
  • $option:It is optional parameter which defines the Bitmask consisting of JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR.
  • $depth:It is optional parameter which sets the maximum depth. Its value must be greater than zero.

Return Value:

This function returns a JSON representation on success or false on failure.

Example : 1
<?php
       
    // Declare an array 
    $value = array(
        "name"=>"MyWebtuts",
        "email"=>"mywebtuts@gmail.com");
       
    // Use json_encode() function
    $json = json_encode($value);
       
    // Display the output
    echo($json);

?>
Output
{"name":"MyWebtuts","email":"mywebtuts@gmail.com"}
Example : 2

This example encodes PHP multidimensional array into JSON representation.

<?php
  
    // Declare two dimensional associative
    // array and initilize it
    $arr = array (
        "first"=>array(
            "id"=>1,
            "product_name"=>"Mobile",
            "cost"=>20000
        ),
        "second"=>array(
            "id"=>2,
            "product_name"=>"TV",
            "cost"=>15000
        ),
        "third"=>array(
            "id"=>3,
            "product_name"=>"Laptop",
            "cost"=>40000
        )
    );

    // Function to convert array into JSON
    echo json_encode($arr);

?>
Output

{"first":{"id":1,"product_name":"Mobile","cost":20000},
"second":{"id":2,"product_name":"TV","cost":15000},
"third":{"id":3,"product_name":"Laptop","cost":40000}}

I Hope It will help you..

Share: