adbario / php-dot-notation

Dot notation access to PHP arrays

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add ability to filter results by value e.g $comedies = $dot->get('movies[genre=comedy]');

talifhani opened this issue · comments

Hey wasn't too sure where to put this so creating an issue. Was thinking of updating the class to be able to do queries like below. Just wanna know if this would get merged. If anyone needs this.

$array = [
    'key1' => 'value1',
    'key2' => 'value2',
    'movies' => [
        [
            'id'    => 1,
            'title' => 'Dumb And Dumber',
            'genre' => 'comedy'
        ],
        [
            'id'    => 2,
            'title' => 'The Mask',
            'genre' => 'comedy'
        ],
        [
            'id'    => 3,
            'title' => 'Eternal Sunshine of the Spotless Mind',
            'genre' => 'drama'
        ],
    ]
];

$comedies = $dot->get('movies[genre=comedy]');

// Commedy would be at the end
$comedies = [
    [
        'id'    => 1,
        'title' => 'Dumb And Dumber',
        'genre' => 'comedy'
    ],
    [
        'id'    => 2,
        'title' => 'The Mask',
        'genre' => 'comedy'
    ],
];

It's not a good idea to mess with the get method on this one, but a separate filter method could be added and that should do the trick. Key/path as a first argument and callback function as a second one.

$comedies = $dot->filter('movies', function($movie) {
    return $movie['genre'] === 'comedy';
});

Having a callback function would be more useful than just hardcoding one option for filtering. This way you can have multiple comparisons and use other operators etc.

I would suggest copying Laravel's Collection. e.g. $dot->get('movies')->where('genre', 'comedy'). This would require get() to return Dot instances instead of plain arrays.