dpd66100 2014-10-01 21:39
浏览 165

将MySQL查询转换为多维数组

I'm having trouble tackling this one. I have a set of data that is returned from a MySQL query like this:

url | users
https://www.facebook.com/ | patrick
https://www.google.com/ | patrick
https://www.reddit.com/ | bob
https://www.bing.com/ | bob
https://www.yahoo.com/ | bertha

where '|' is the field separator.

I need to parse this data using PHP to form a multidimensional array that looks like this:

patrick
   https://www.facebook.com/
   https://www.google.com/
bob
   https://www.reddit.com/
   https://www.bing.com/
bertha
   https://www.yahoo.com/

Any assistance would be appreciated.

  • 写回答

1条回答 默认 最新

  • dpca31461 2014-10-01 21:45
    关注

    Assuming you know how to get results out of the database with PHP, I would go with something like this;

    while($row = $result->fetch_assoc()) {
        $array[$row['users']][] = $row['url'];
    }
    

    You will get an array with the user as the first key, and a numeric as the second, with the url as the value, as follows;

    Array (
       patrick => Array (
                  [0] => https://www.facebook.com/
                  [1] => https://www.google.com/
       )
       bob => Array (
                  [0] => https://www.reddit.com/
                  [1] => https://www.bing.com/
       )
       bertha => Array (
                  [0] => https://www.yahoo.com/
       )
    )
    

    Note: I have used the object orientated style mysqli function here. If you are still using mysql_ functions, please migrate to either MySQLi or PDO as soon as possible.

    Hope this helps.

    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘