2013-03-10 114 views
0

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

如表有以下栏目:

Groupname 
Groupid 
Groupurl 

我想调用这个方法是:

$arrayname[groupname][1]; 

我已经形成了2个阵列已经分别是:

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

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

我似乎无法得到一个循环加入数组作为一个多维对象,我可以手动执行此特定表,同时,它是一类函数,变量可变部分是打破我= \

================感谢IMSoP给了我这个想法,解决方案是==================

$结果函数是一个成功的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; 

} 
+0

在什么地方 “变量变量” $$来colname'而来?为什么你不能简单地填充'$ return [$ colname]'? – IMSoP 2013-03-10 21:52:15

+0

感谢IMSoP,谁给了我这个想法,我在原来的帖子中提出以下内容! – Hawkwah 2013-03-11 10:12:34

+1

[**请勿在新代码**中使用'mysql_ *'函数](http://bit.ly/phpmsql)。他们不再被维护[并且被正式弃用](http://j.mp/XqV7Lp)。看到[**红框**](http://j.mp/Te9zIL)?学习[*准备的语句*](http://j.mp/T9hLWi),并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [这篇文章](http://j.mp/QEx8IB)将帮助你决定哪个。如果你选择PDO,[这里是一个很好的教程](http://j.mp/PoWehJ)。 – 2013-03-11 10:18:16

回答

0

我使用的功能是:

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; 

}