PHP - Ds Vector::jsonSerialize() Function
The PHP Ds\Vector::jsonSerialize() function is used to retrieve a representation of elements that can be converted to JSON format.
The JSON stands for "JavaScript Object Notation" is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute-value pairs and arrays.
Note: This function should never be called directly.
Syntax
Following is the syntax of the PHP Ds\Vector::jsonSerialize() function −
public JsonSerializable::jsonSerialize(): mixed
Parameters
This function does not accept any parameter.
Return value
This function returns the representation that can be converted to JSON.
Example 1
The following is the basic example of the PHP Ds\Vector::jsonSerialize() function −
<?php
class Demo implements JsonSerializable {
public function __construct(array $my_arr) {
$this->array = $my_arr;
}
public function jsonSerialize(){
return $this->array;
}
}
$my_arr = [10, 20, 30, 40, 50];
echo "The elements before converting to JSON format: \n";
print_r($my_arr);
echo "The elements after converting to JSON format: \n";
echo json_encode(new Demo($my_arr), JSON_PRETTY_PRINT);
?>
Output
The above program displays the following output −
The elements before converting to JSON format:
Array
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
[4] => 50
)
The elements after converting to JSON format:
[
10,
20,
30,
40,
50
]
Example 2
Following is another example of the PHP Ds\Vector::jsonSerialize() function. We use this function to retrieve a representation that can be converted to JSON format −
<?php
class Demo implements JsonSerializable {
public function __construct(array $vowels) {
$this->array = $vowels;
}
public function jsonSerialize(){
return $this->array;
}
}
$vowels = ['a', 'e', 'o', 'i', 'u'];
echo "The elements before converting to JSON format: \n";
print_r($vowels);
echo "The elements after converting to JSON format: \n";
echo json_encode(new Demo($vowels), JSON_PRETTY_PRINT);
?>
Output
After executing the above program, the following output will be displayed:
The elements before converting to JSON format:
Array
(
[0] => a
[1] => e
[2] => o
[3] => i
[4] => u
)
The elements after converting to JSON format:
[
"a",
"e",
"o",
"i",
"u"
]