I use a GET request to access an API. I first filter the returned data like this:
$results = array_filter($body, function($item) {
if(!isset($item['schedule']['type']))
return false;
return $item['schedule']['type'] == "weekly";
});
Condensed version of the returned array:
array (
6 =>
array (
'foo' => 'other fields x 100',
'title' => 'Episode 1 Title',
'automatically_title_stream' => false,
'stream_title' => 'Episode 1 Title',
'stream_description' => 'Join us each afternoon for real-time market analysis and live futures trading in this interactive live stream event.',
'rtmp_link' => 'rtmp://rtmp-global.cloud.vimeo.com/live',
'rtmps_link' => 'rtmps://rtmp-global.cloud.vimeo.com:443/live',
'stream_key' => '97deb5f6-9bef-4e1c-91f8-d39f72657290',
'schedule' =>
array (
'type' => 'weekly',
'start_time' => NULL,
'daily_time' => '19:15:00Z',
'scheduled_time' => NULL,
'weekdays' =>
array (
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5,
),
),
),
7 =>
array (
'foo' => 'other fields x 100',
'title' => 'Episode 2 Title',
'automatically_title_stream' => false,
'stream_title' => 'Bars Closing',
'stream_description' => 'Join us each afternoon for real-time market analysis and live futures trading in this interactive live stream event.',
'rtmp_link' => 'rtmp://rtmp-global.cloud.vimeo.com/live',
'rtmps_link' => 'rtmps://rtmp-global.cloud.vimeo.com:443/live',
'stream_key' => '97deb5f6-9bef-4e1c-91f8-d39f72657290',
'schedule' =>
array (
'type' => 'weekly',
'start_time' => NULL,
'daily_time' => '19:15:00Z',
'scheduled_time' => NULL,
'weekdays' =>
array (
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5,
),
),
)
)
This works in the fact it only returns objects with a [‘schedule’][‘type’] == "weekly". The problem is that the array is HUGE, over 56K lines. I do not need all of it, only certain fields.
I want to filter it again, after I’ve returned the "weekly" data, and only return "title", "stream_description" and the "weekdays" values. However, I get an empty array when filtering like this:
$allowed = ['title', 'stream_description', 'weekdays'];
$filtered = array_filter(
$results,
fn ($key) => in_array($key, $allowed),
ARRAY_FILTER_USE_KEY
);
I have other, more complex arrays to filter as well. How do I create a new array from only a specified list of key’s and eliminate all the unnecessary data from the array?
2
Answers
You’re filtering the main array, but you need to filter the nested arrays. For that you should use
array_map()
to process each nested array. And some of your allowed keys are nested further down — this makes it difficult to use a simplearray_filter
on the keys.Simplify it to just return the 3 keys you want in code.
I’m old school and like to keep things simple.
I’d just use a
foreach()
I think this may be what you were trying to do.
The results: