I have following multi dimensional array, I’m getting this from an API via curl request.
Array
(
[0] => Array
(
[id] => 1
[name] => David Warner
[type] => batter
[country] => Aus
[age] => 33
[runs] => 11100
[wickets] => 12
[catches] => 16
[format] => Array
(
[0] => Array
(
[Domestic] => Array
(
[0] => Array
(
[ODI] => 73
[Tests] => 34
[T20] => 90
)
)
)
)
)
[1] => Array
(
[id] => 2
[name] => Mark Wood
[type] => bowler
[country] => Eng
[age] => 34
[runs] => 200
[wickets] => 120
[catches] => 2
[format] => Array
(
[0] => Array
(
[Domestic] => Array
(
[0] => Array
(
[ODI] => 40
[Tests] => 49
[T20] => 12
)
)
)
)
)
)
I’m trying to create a new array which includes only the "[T20]" values.
My desired out put should look similar to the following array
array:2 [▼
0 => "90"
1 => "12"
]
So far, I’ve tried following methods…
$newArr_t20 = array_column($result_3['cricketers']['player']['format']['Domestic'], "T20");
Since I’m using laravel then I tried following as well,
use IlluminateSupportArr;
$newArr_t20 = Arr::pluck($result_3, 'cricketers.player.format.Domestic.T20');
But nothing is working for me…
2
Answers
Using Laravel the collection helper
Collection::flatten()
should be the right way;Explanation:
Transform your array into a collection to be able to use the Laravel collection’s provided helpers:
collect($apiData)
Transform your multidimensional array into a single dimensional one, which is nothing more than the array at the n-th depth (4 here in this case):
collect($apiData)->flatten(4)
Map this array into an array having only the values of the
T20
keycollect($apiData)->flatten(4)->pluck('T20')
Get the array representation of the collection
collect($apiData)->flatten(4)->pluck('T20')->all()
You can try this: