Tuesday, November 19, 2024
Google search engine
HomeLanguagesPHP | DsVector jsonSerialize() Function

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:




<?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);
  
?>


Output:

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

Program 2:




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


Output:

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

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments