PHP | Ds\Vector jsonSerialize() Function

The Ds\Vector::jsonSerialize() function is an inbuilt function in PHP which is used to return the element which can be converted to JSON.

Syntax:

mixed public JsonSerializable::jsonSerialize( void )

Parameters: This function does not accepts any parameter.



Return Value: This function returns the values of the vector in the form which can be converted to JSON.

Below programs illustrate the Ds\Vector::jsonSerialize() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
class vector implements JsonSerializable {
    public function __construct(array $arr) {
        $this->array = $arr;
    }
  
    public function jsonSerialize() {
        return $this->array;
    }
}
  
// Declare an array
$arr = [1, 2, 3, 4, 5];
  
echo("Elements after converting to JSON convertible form\n");
  
echo json_encode(new vector($arr), JSON_PRETTY_PRINT);
  
?>

chevron_right


Output:

Elements after converting to JSON convertible form
[
    1,
    2,
    3,
    4,
    5
]

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
class vector implements JsonSerializable {
    public function __construct(array $arr) {
        $this->array = $arr;
    }
  
    public function jsonSerialize() {
        return $this->array;
    }
}
  
// Declare an array
$arr = ["geeks", "for", "geeks"];
  
echo("Elements after converting to JSON convertible form\n");
  
echo json_encode(new vector($arr), JSON_PRETTY_PRINT);
  
?>

chevron_right


Output:

Elements after converting to JSON convertible form
[
    "geeks",
    "for",
    "geeks"
]

Reference: http://php.net/manual/en/ds-vector.jsonserialize.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.