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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231

1 Answers1

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.

samrap
  • 5,595
  • 5
  • 31
  • 56
  • Unfortunately the first option as you said puts everything in dot notation. I would like it to be in the same format. – Yahya Uddin Mar 20 '18 at 16:42
  • Take a look at this: https://stackoverflow.com/questions/9635968/convert-dot-syntax-like-this-that-other-to-multi-dimensional-array-in-php – samrap Mar 20 '18 at 16:53