【问题标题】:PHP: Sorting MySQL result to multi-dimensional arrayPHP:将MySQL结果排序为多维数组
【发布时间】:2014-12-04 22:37:06
【问题描述】:

现在我正在尝试通过 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: 所以我尝试使用foreachecho 我的数组,它从我的数据库返回只有一行。 我做错了什么?

【问题讨论】:

  • 您只得到一行,因为您在 while() 之前调用了 mysql_fetch_assoc($front_end_query_result),这将取出第一行。删除它,你会得到你的两行。
  • @Samsquanch 我在测试前评论了while()
  • 如果你注释掉 while 那么你只会得到一个结果。这就是时间的用途。 mysql_fetch_assoc 只返回一个结果。

标签: php mysql arrays


【解决方案1】:
$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;
    }
}

【讨论】:

  • 抱歉,我在定义 $someResult$someIdentifier 的地方不明白?
  • 抱歉,只是在php 中展示了如何制作多维数组的一般模式。对于您的具体情况,请使用第二种形式。我也会编辑我的答案以澄清。
  • 好的,但我看不出我需要在哪里定义$someValue。对不起,但我真的无法理解你的例子。
猜你喜欢
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 2011-06-30
  • 2013-10-12
  • 1970-01-01
相关资源
最近更新 更多