duanji1902 2017-07-19 01:20
浏览 31
已采纳

使用多行填充PHP数组

I am running a SQL Query in php and returning the results like this

Name
Joe
Jack
Jerri
Jerry

I need to parse this into a php array and unfortunately, the method I have used in the past to add to a php array is no longer relevant since I am returning multiple rows. How would I alter this syntax in order to account for one column with multiple rows to populate my php array?

$rows = $db->loadRowList();
$output = array();
foreach ($rows as $row) { array_push($output, $row); }
$data = json_encode($output[0]);
  • 写回答

1条回答 默认 最新

  • dongqu4443 2017-07-19 02:01
    关注

    TL;DR: Use loadAssocList('id', 'name')


    loadRowList() returns an indexed array of indexed arrays from the table records returned by the query

    Thus, I'll assume the $rows array looks something like this:

    Array
    (
        [0] => Array
            (
                [0] => Joe
            )
    
        [1] => Array
            (
                [0] => Jack
            )
    
        [2] => Array
            (
                [0] => Jerri
            )
    
        [3] => Array
            (
                [0] => Jerry
            )
    )
    

    You can use PHP's array_column() to fetch a single index value from every child array:

    $rows = $db->loadRowList();
    $output = array_column($rows, 0);
    

    $output should now contain an array looking like:

    Array
    (
        [0] => Joe
        [1] => Jack
        [2] => Jerri
        [3] => Jerry
    )
    

    An improvement we can make here is to maintain an associative array, that maps your database's column names to their values. loadAssocList() can help there.

    $rows = $db->loadAssocList();
    $output = array_column($rows, 'name');
    

    Note that we now use the "name" index instead of 0.

    This can be even further improved by utilizing the parameters of loadAssocList():

    loadAssocList($key, $column) returns an associative array, indexed on 'key', of values from the column named 'column' returned by the query

    Using this method, we can receive a single array in ID => Name key value format:

    $ouput = $db->loadAssocList('id', 'name');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?