duannao8450 2016-03-13 09:32
浏览 49
已采纳

PHP pdo获取结果集中键的所有值

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.

展开全部

  • 写回答

1条回答 默认 最新

  • duanfu9523 2016-03-13 09:35
    关注

    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
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部