Using JSON in PHP: json_encode and json_decode Explained with Examples
This article explains the fundamentals of JSON, its syntax rules, and demonstrates how PHP's json_encode and json_decode functions convert between arrays and JSON strings, including examples of sequential, non‑sequential, and multidimensional arrays, and the effect of the associative‑array option.
JSON is a lightweight data-interchange format widely used in network communication, supported by almost all programming languages.
The article outlines the basic syntax rules of JSON: key‑value pairs, comma separation, curly braces for objects, and square brackets for arrays.
In PHP, the json_encode() function converts arrays to JSON strings. Example code demonstrates encoding a sequential array, a non‑sequential array, the effect of unsetting an element, and encoding a two‑dimensional array:
<?php
echo "连续数组";
$sequential = array("foo","bar","baz","blong");
echo json_encode($sequential);
echo "<br/>非连续数组";
$nonsequential = array(1=>"foo",2=>"bar",3=>"baz",4=>"blong");
echo json_encode($nonsequential);
echo "<br/>删除一个连续数组值的方式产生的非连续数组";
unset($sequential[1]);
echo json_encode($sequential);
echo "<br/>二维数组";
$arr = array(array('name'=>'chenxiaolong'),array('name'=>'zhangsan'));
echo json_encode($arr);
?>When encoding a two‑dimensional array, the outermost JSON structure is an array (enclosed in square brackets) containing the JSON representations of each inner array.
The json_decode() function parses JSON strings back into PHP variables. By default it returns an object; passing true as the second argument returns an associative array. Example code shows decoding a JSON string to an object and to an array:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
echo "<br/>";
var_dump(json_decode($json,true));
?>The article concludes that setting the second parameter of json_decode() to true converts JSON data into an array.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
