Php 将mysql结果输出为表单数组(列名=>;列名的可能值)
我有一个数据库,比如 我想创建一个关联数组,使每个Php 将mysql结果输出为表单数组(列名=>;列名的可能值),php,mysql,associative-array,Php,Mysql,Associative Array,我有一个数据库,比如 我想创建一个关联数组,使每个att_name值与其att_value中的可能值相关联: array('att_name' => array('att_value_1', 'att_value_2', 'att_value_3')) 实现这一目标的最佳方法是什么?请尝试以下方法: $sql = "SELECT * from tablename"; $result = mysql_query($sql,$con); $final_array=array(); whi
att_name
值与其att_value
中的可能值相关联:
array('att_name' => array('att_value_1', 'att_value_2', 'att_value_3'))
实现这一目标的最佳方法是什么?请尝试以下方法:
$sql = "SELECT * from tablename";
$result = mysql_query($sql,$con);
$final_array=array();
while ($row = mysql_fetch_object($result))
{
$final_array[$row->att_name][0]=$row->att_value_1;
$final_array[$row->att_name][1]=$row->att_value_2;
....
....
}
请尝试以下内容:
$sql = "SELECT * from tablename";
$result = mysql_query($sql,$con);
$final_array=array();
while ($row = mysql_fetch_object($result))
{
$final_array[$row->att_name][0]=$row->att_value_1;
$final_array[$row->att_name][1]=$row->att_value_2;
....
....
}
这样:
SELECT
item,
att_name,
GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value
FROM
table
GROUP BY
att_name
这样:
SELECT
item,
att_name,
GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value
FROM
table
GROUP BY
att_name
虽然只需选择所需的结果并在PHP中迭代以创建所需的数据结构,就可以轻松做到这一点,但您可以使用以下方法将部分工作分为MySQL: 当然,这只有在您的值永远不包含MySQL查询中用于分隔符的字符(或字符序列)时才有效,因此更安全的纯PHP方法是:
$query = "
SELECT att_name, att_value
FROM table_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']][] = $row['att_value'];
}
print_r($array);
虽然只需选择所需的结果并在PHP中迭代以创建所需的数据结构,就可以轻松做到这一点,但您可以使用以下方法将部分工作分为MySQL: 当然,这只有在您的值永远不包含MySQL查询中用于分隔符的字符(或字符序列)时才有效,因此更安全的纯PHP方法是:
$query = "
SELECT att_name, att_value
FROM table_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']][] = $row['att_value'];
}
print_r($array);
mysql\u fetch\u assoc
当然……以您想要的任何方式获取行,然后迭代它们并以您想要的格式创建一个新数组。没有SQL查询可以为您生成该格式。这很简单,我建议您更熟悉数组:也许还有mysql\u fetch.*
函数:。为什么要创建这样的数组mysql\u fetch\u assoc
为您提供一个(键、值)数组。感谢大家的帮助,这很有帮助,抱歉没有投票!;我没有必要投票了mysql\u fetch\u assoc
当然……以您想要的任何方式获取行,然后迭代它们并以您想要的格式创建一个新数组。没有SQL查询可以为您生成该格式。这很简单,我建议您更熟悉数组:也许还有mysql\u fetch.*
函数:。为什么要创建这样的数组mysql\u fetch\u assoc
为您提供一个(键、值)数组。感谢大家的帮助,这很有帮助,抱歉没有投票!;我没有必要投票了!!