PHP:将MySQL结果排序为多维数组

时间:2014-10-09 21:04:09

标签: php mysql arrays

现在我试着通过SQL中的type行将MySQL结果排序到多维数组 所以,这是我的代码:

function getTableValues($table_name)
{
//    $link = connect_db();
    $front_end_query = "SELECT * FROM `".$table_name."` WHERE  `type` =  'front_end'";
    $front_end_query_result = mysql_query($front_end_query);

    $cur_row = 0;   
    /*while ($line = mysql_fetch_assoc($queryresult)) 
    {
        $values = $line;
        $cur_row++;
    }*/
    $front_end = mysql_fetch_assoc($front_end_query_result);
    $i=0;
    while ($line = mysql_fetch_assoc($front_end_query_result)){
        #if ($line['type'] === 'front_end'){
        #    $line[$line['type']][$line['name']] = $line['value'];
        #    $line[$line['type']][$line['name']]['desc'] = $line['description'];
        #    $line[$line['type']][$line['name']]['visible_name'] = $line['visible_name'];
        #    $line[$line['type']][$line['name']]['write_roles'] = $line['write_roles'];
        #    $line[$line['type']][$line['name']]['read_roles'] = $line['read_roles'];
        #}

        $values['front_end'][$line['name']] = $line;
        $i++;
    }

    return $values;
}

我的MySQL表:

id type      write_roles read_roles name        value     description      visible_name     
1  front_end 0           any        title       sometitle exampletitle     Title     
2  front_end 0           any        description somedesc  example          Description     

这就是我想要的:

$config[(someType)][(SomeName)] = (value of line)
$config[(someType)][(SomeName)][(SomeOption)] = (value of option)    
例如,返回$config['front_end']['title']['description']

exampletitle

我怎么能这样做?

UPD0:所以我尝试使用echo foreach我的数组,并从我的数据库返回一行。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

$values = array(); //base array
while ($line = mysql_fetch_assoc($front_end_query_result)){ //fetch the rows
    //in the base array create a new array under 'name'
    $values[$line['name']] = array(); 
    //for each item in the result set, add it to the new array
    foreach ($line as $key => $value) {
        $values[$line['name']][$key] = $value;
    }
}