Search code examples
phparraysfilteringassociative-arraywhitelist

Filter an associative array to only retain elements with whitelisted keys


I am having array like below.

$a = [
    [id] => 18162876
    [name] => phpuG4fhx
    [type] => Video
    [created] => 2016-02-11T16:55:54+00:00
    [updated] => 2016-02-11T16:55:54+00:00
    [duration] => 14.975
    [hashed_id] => uzyng792la
    [description] => 
    [progress] => 0
    [status] => queued
    [thumbnail] => Array
        (
            [url] => https://embed-ssl.wistia.com/deliveries/c2b1eb4bdf6f872fb9da416994973a5358b31868.jpg?image_crop_resized=200x120&video_still_time=7
            [width] => 200
            [height] => 120
        )

    [account_id] => 410090];

In that, I need to fillter only [hashed_id] and [thumbnail].


Solution

  • Not entirely sure what you are asking but...

    If you want to access the elements of the array you can use the following format:

    $array[$key]

    For your example it would be: $a['hashed_id']

    If you want to filter the array so it only contains the hashed_id and the thumbnail then you could do something like:

    $filteredArray = [];
    $filteredArray['hashed_id'] = $a['hashed_id'];
    $filteredArray['thumbnail'] = $a['thumbnail'];
    

    And then you have an array only containing the hashed_id and the thumbnail.

    If that answers your question, great; if not you may want to clarify what it is your after after you 'filter' your array. What is your expected outcome, etc?