我有数据库,如
我想创建一个关联数组,以便每个att_name
值都与其可能的值相关联att_value
:
array('att_name' => array('att_value_1', 'att_value_2', 'att_value_3'))
实现这一目标的最佳方法是什么?
我有数据库,如
我想创建一个关联数组,以便每个att_name
值都与其可能的值相关联att_value
:
array('att_name' => array('att_value_1', 'att_value_2', 'att_value_3'))
实现这一目标的最佳方法是什么?
虽然很容易做到这一点,只需选择您想要的结果并在 PHP 中迭代它们以创建您想要的数据结构,您可以将一些工作分给 MySQL GROUP_CONCAT()
:
$query = "
SELECT att_name, GROUP_CONCAT(att_value SEPARATOR ',') AS values
FROM table_name
GROUP BY att_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']] = explode(',', $values);
}
print_r($array);
当然,这仅在您的值永远不会包含您SEPARATOR
在 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);
试试下面:
$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;
....
....
}
This way :
SELECT
item,
att_name,
GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value
FROM
table
GROUP BY
att_name
Will give you something like that :
item att_name att_value
-----------------------------
books height 150 mm<!>250 mm
books price rs:20<!>Rs:20
books size 15 pg<!>30 pg<!>60 pg
books width 300 mm<!>400 mm
You have to explode the result from att_value
by a <!>
. I use this <!>
so it highly impossible to have a value inside att_value
with this. If you think you would someday use this, take another separator. Example : [{--}]
, _SEPARATOR_
, [_-CUT-_]
, etc. Something you are sure at 100% you won't use a choice but always as a separator to split the text.
So example :
$SQL = 'SELECT item, att_name, GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value FROM table GROUP BY att_name';
$Query = mysql_query($SQL) or die('MySQL Error : '.mysql_error());
while($Assoc = mysql_fetch_assoc($Query)){
$Assoc['att_value'] = ($Assoc['att_value'] != '' ? explode('<!>', $Assoc['att_value']) : NULL);
print_r($Assoc);
}