【问题标题】:Creating multidimensional array from existing arrays with variable variables从具有可变变量的现有数组创建多维数组
【发布时间】:2013-03-10 21:40:09
【问题描述】:

我正在创建一个类函数,它接受 mysql 查询结果并返回一个多维数组,其中第一个数组指针是表列,第二个指针是它在 MySQL 数据中位置的数字指示符。

例如,表格有以下列:

Groupname
Groupid
Groupurl

我想这样称呼它:

$arrayname[groupname][1];

我已经形成了 2 个数组,它们是:

$colnames 包含来自特定 mysql 查询的所有列和

$$colname是列名的变量变量,包含每一列的所有数据。例如:$groupurl 是一个包含该列中所有数据的数组。

我似乎无法获得一个循环来将数组作为多维对象加入,虽然我可以为特定表手动执行此操作,但它是一个类函数,变量变量部分让我崩溃=\

================感谢IMSoP给我的想法,解决方案是==================

函数中的$result是一个成功的MySQL查询表。

function tableAsMatrix($result)
{
    //declare $results as array for use in loop
    $results = array();

    //this gets all the col names and sets them as $colnames[]
    while( $cols = $result->fetch_field() )
    {
        $colnames[] = $cols->name;
    }

    //this loops through and assigns all cols as multidimensional $results[colname][id]
    foreach ($colnames as $fields)
    {
        while ($row = $result->fetch_array(MYSQLI_ASSOC))
        {
           foreach($colnames as $field)
           {
               $results[$field][] = $row[$field];
           }
        }
    }

    //return to object
    return $results;

}

【问题讨论】:

标签: php mysql arrays multidimensional-array


【解决方案1】:

我使用的函数是:

function tableAsMatrix($result)
{
    //declare $results as array for use in loop
    $results = array();

    //this gets all the col names and sets them as $colnames[]
    while( $cols = $result->fetch_field() )
    {
        $colnames[] = $cols->name;
    }

    //this loops through and assigns all cols as multidimensional $results[colname][id]
    foreach ($colnames as $fields)
    {
        while ($row = $result->fetch_array(MYSQLI_ASSOC))
        {
           foreach($colnames as $field)
           {
               $results[$field][] = $row[$field];
           }
        }
    }

    //return to object
    return $results;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-26
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多