class JsonPath

This class allows arbitrary data structures to be inserted into, and extracted from, deep arrays and JSON-serialized strings. Say, for example, that you have this array as an input:

['foo' => ['bar' => ['baz' => 'some_value']]]

and you wanted to insert or extract an element. Usually, you would use:

$array['foo']['bar']['baz'] = 'new_value';

but sometimes you do not have access to the variable - so a string representation is needed. Using XPath-like syntax, this class allows you to do this:

$jsonPath = new JsonPath($array);
$jsonPath->set('foo.bar.baz', 'new_value');
$val = $jsonPath->get('foo.bar.baz');

Methods

__construct ($structure)

No description

set (string $path, $value)

Set a node in the structure

getStructure () : mixed

Return the updated structure.

get (string $path) : mixed|null

Get a path's value. If no path can be matched, NULL is returned.

Details

__construct($structure)

Parameters

$structure The initial data structure to extract from and insert into. Typically this will be a multidimensional associative array; but well-formed JSON strings are also acceptable.

Example code

$jsonPath->__construct($structure);

set(string $path, $value)

Set a node in the structure

Parameters

$path string The XPath to use
$value The new value of the node

Example code

$jsonPath->set($path, $value);

getStructure()

Return the updated structure.

Return value

mixed

Example code

$mixed = $jsonPath->getStructure();

get(string $path)

Get a path's value. If no path can be matched, NULL is returned.

Parameters

$path string

Return value

mixed|null

Example code

$response = $jsonPath->get($path);