PHP code example of rugolinifr / array-path-selector

1. Go to this page and download the library: Download rugolinifr/array-path-selector library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rugolinifr / array-path-selector example snippets


$flattener = (new Rugolinifr\ArrayPathSelector\Factory\PathToolFactory())->createFlattener();

$array = [
    'name' => 'John Doe',
    'address' => [
        'city' => 'Nice',
        'zips' => [
            '06000',
            '06100',
        ],
        'street' => 'Promenade des anglais',
    ],
    'birth' => new DateTimeImmutable('1980-01-01 12:00:00'),
    'kids' => [],
];

// flatten an array following the "key/value" model:
$keyValues = $flattener->flattenAsKeyValues($array);
$keyValues === [
    'name' => 'John Doe',
    'address.city' => 'Nice',
    'address.zips[0]' => '06000',
    'address.zips[1]' => '06100',
    'address.street' => 'Promenade des anglais',
    'birth' => new DateTimeImmutable('1980-01-01 12:00:00'),
    'kids' => [], //empty arrays have their own entry, otherwise they would disappear from the flattened array
];

$pairs = $flattener->flattenAsPairs($array);
$keyValues === [
    0 => ['name', 'John Doe'],
    1 => ['address.city', 'Nice'],
    2 => ['address.zips[0]', '06000'],
    3 => ['address.zips[1]', '06100'],
    4 => ['address.street', 'Promenade des anglais'],
    5 => ['birth', new DateTimeImmutable('1980-01-01 12:00:00')],
    6 => ['kids', []], //empty arrays have their own entry, otherwise they would disappear from the flattened array
];

$crud = (new Rugolinifr\ArrayPathSelector\Factory\PathToolFactory())->createCrud();

$array = [
    'name' => 'John Doe',
    'kids' => [],
];

// Create new arrays along the property path:
$crud->put($array, 'address.city', 'Nice');
$crud->put($array, 'address.zips[0]', '06000');

$array === [
    'name' => 'John Doe',
    'kids' => [],
    'address' => [
        'city' => 'Nice',
        'zips' => [
            '06000',
        ],
    ],
];

// Get a value:
$crud->get($array, 'name') === 'Jane Doe';

// Replace a value:
$crud->put($array, 'name', 'Jane Doe');

// Delete a value:
$crud->delete($array, 'kids');
$crud->delete($array, 'address.zips[0]');

$array === [
    'name' => 'Jane Doe',
    'address' => [
        'city' => 'Nice',
        'zips' => [],
    ],
];
shell
docker compose exec php phpstan analyze
docker compose exec php vendor/bin/phpunit tests