0

Let's say for example you have a constant multi-dimensional array with multiple keys (and values), but you want to filter out specific keys with it's values. See a example array below:

const defaultInvestmentFields = [
     [
         'type' => 'system',
         'investment_name' => 'Ballast'
     ],
     [
         'type' => 'system',
         'investment_name' => 'Inverters'
     ],
        [
         'type' => 'system',
         'investment_name' => 'Extra garantie inverters'
     ]
];

The output I want is an array with only the values of investment_name. Like ['Ballast', 'Inverters', 'Extra garantie inverters'].

1
  • 1
    array_column is function name. Commented Aug 5, 2021 at 11:01

2 Answers 2

3

Additionally to @Levi's answer, you can use an array helper to avoid having to transform the array into a collection and back: Arr::pluck()

Arr::pluck(Project::defaultInvestmentFields, 'investment_name');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer! It's way faster, but transforming it to a collection will give more flexibility.
You're welcome. Sure, flexibility where flexibility is due.
1

A quick and neat solution would be to use the collect wrapper function which is provided by Laravel. After that we can use the pluck function in order to specify which values by their key(s) we want to get. For example:

collect(Project::defaultInvestmentFields)->pluck('investment_name');

Now we have a Collection of the following values: Ballast, Inverters and Extra garantie inverters. In order to use it as an array, simply call toArray() on it.

Comments

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.