0

I am trying to find a way to get all the data that is returned from my mysql query to be fetched as per the key, such that I get all the values for that specific key, For example if this is the array of results I get from my pdo fetchAll() method ,

Array
(
    [0] => Array
        (
            [name] => user1
            [country] => USA
        )

    [1] => Array
        (
            [name] => user2
            [country] => Canada
        )

    [2] => Array
        (
            [name] => user3
            [country] => Iceland
        )

    [3] => Array
        (
            [name] => user4
            [country] => Scotland
        )

)

what is the best way to fetch all the countries from this result array? I am not so good with looping over multi-dimensional arrays. sorry if this is a very silly question I'm still a beginner in PHP.

Fred
  • 3
  • 2

1 Answers1

0

PHP provides a handy function called array_column() for this purpose, you can pass the key as an parameter to this function call and it will return an array of columns' data,

Please make sure you're using PHP 5.5 or greater for this to work

$result_set = YOUR_RESULT_ARRAY_HERE;
print_r(array_column($result_set, 'country'));

//output
Array
(
    [0] => USA
    [1] => Canada
    [2] => Scotland
    [3] => Iceland
)
Vishnu Nair
  • 2,395
  • 14
  • 16