Skip to content
Advertisement

PHP Nested Array – extract specific items from array

i have the following array of data following a json_decode that i would like to extract all instances of [id] (except the ones under [contact]) to another array. I have tried array_column, but not getting the expected results. Any help would be much appreciated:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [firstName] => John
                    [lastName] => Doe
                    [photoURL] => 
                    [Contact] => Array
                        (
                            [id] => 43534554542
                            [type] => contacts
                        )

                    [webUrl] => https://www.google.com
                    [id] => extract_this_id
                )

            [1] => Array
                (
                    [firstName] => John
                    [lastName] => Doe
                    [photoURL] => 
                    [Contact] => Array
                        (
                            [id] => 43534554543
                            [type] => contacts
                        )

                    [webUrl] => https://www.google.com
                    [id] => extract_this_id
                )
        )
)

Advertisement

Answer

array_column should work. Just make sure you look in the “data” key. So assuming your input is stored in $response, it would be:

$result = array_column($response["data"], "id");

See it run in this sandbox

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement