LovinQuaQua
LovinQuaQua

Reputation: 123

get specific values of a multidimensional array in php

I am searching for the best way to get specific values in a multidimensional array. My array looks like this. I dont know how many Arrays i get back so i need this in a foreach.

e.g. I want now to return from every array the [event_budget][0] value. How can i achieve this?

Array
(
    [0] => Array
        (
            [event_budget] => Array
                (
                    [0] => Bis € 4000
                )

            [event_date] => Array
                (
                    [0] => 27.10.2019
                )

            [event_date_timestamp] => Array
                (
                    [0] => 1572134400
                )

        )

    [1] => Array
        (
            [event_budget] => Array
                (
                    [0] => Bis € 500
                )

            [event_date] => Array
                (
                    [0] => 29.10.2019
                )

            [event_date_timestamp] => Array
                (
                    [0] => 1572307200
                )

        )

)

Upvotes: 0

Views: 56

Answers (3)

Vivek V Nair
Vivek V Nair

Reputation: 217

There are different ways in which you can get your required result.

The most basic :

$finalArray = array();
foreach($result as $key => $value){
  $finalArray[] = $value['event_budget'][0];
}

The $finalArray will have your required result. You can also use like @rakesh have mentioned.

array_map('array_shift',array_column($a, 'event_budget'));

It would be great if you have control over the main array. If that is the case you can avoid event_budget to be an array.

If possible, it should be made like this:


[event_budget] => Array ( [0] => Bis € 500 )


[event_budget] => Bis € 500


Hope it was helpful. Thanks

Upvotes: 1

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You can use array_map with array_column and array_shift

$aa = array_map('array_shift',array_column($a, 'event_budget'));
print_r($aa);

Working example : https://3v4l.org/fKpjY

Upvotes: 0

u_mulder
u_mulder

Reputation: 54796

Start with:

print_r(array_column($array, 'event_budget'));

But as event_budget is array too, you need to get columns with index 0:

print_r(array_column(
    array_column($array, 'event_budget'), 
    0
));

Full demo.

Upvotes: 0

Related Questions