2

I am using Laravel 5.6. I want a function that returns only the specified key / value pairs from the given array using the dot notation.

For example:

$array = [
    'name' => [
        'first' => 'John', 
        'last' => 'Smith'
    ], 
    'price' => 100,
    'orders' => 10
];


$slice = someFunc($array, ['name.first', 'price']);

should return:

[
    'name' => [
        'first' => 'John'
    ],
    'price' => 100,
]

The closest function that does this is in Laravel that I can find is the array_only function:

https://laravel.com/docs/5.6/helpers#method-array-only

However, it does not support the dot notation (unlike some other Laravel functions).

How can I achieve this?

4
  • What about array_get? Commented Mar 20, 2018 at 16:29
  • You could combine array_dot and array_only, e.g: array_only(array_dot($array), ['name.first', 'price']); and if you need it to be a single function then you could add your own helper that wraps these 2 functions. Commented Mar 20, 2018 at 16:32
  • Tryied $array = collect($array); $array->get('name.first'); but it sends me null. Commented Mar 20, 2018 at 16:41
  • try this packagist.org/packages/adbario/php-dot-notation Commented Mar 20, 2018 at 18:20

1 Answer 1

2

There's two options you could use off the top of my head. The first is to use array_dot to flatten a multi-dimensional array into a one dimensional dot notated array:

$flattened = array_dot([
    'name' => [
        'first' => 'John', 
        'last' => 'Smith'
    ], 
    'price' => 100,
    'orders' => 10
]);

This would yield the following result:

[
    'name.first' => 'John',
    'name.last' => 'Smith',
    'price' => 100,
    'orders' => 10,
]

From there you can get everything except orders using array_except($flattened, 'orders'). Of course, the resulting array will still be in dot notation which may not be ideal for you.

The second option I can think of is merging multiple calls to array_get, since it supports dot notation.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately the first option as you said puts everything in dot notation. I would like it to be in the same format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.