我还没有在PHP中使用过很多数组。我有一张颜色表。我想将它加载到一个多维关联数组中,因为我将大量使用该表,并且不想一遍又一遍地进行选择。
我做了:
$result = mysql_query("select * FROM color") or die(mysql_error());
$colors = "";
while($colorrec = mysql_fetch_array($result)){
$colors[$colorrec['ID']][0] = $colorrec['Description'];
$colors[$colorrec['ID']][1] = $colorrec['HexCode'];
}
然后当我想访问颜色信息时,我可以做类似的事情:
echo "color code WHT";
echo "description ".$colors['WHT'][0];
echo "Hex Code ".$colors['WHT'][1];
这是正确的方法/方法吗?
答案 0 :(得分:1)
$colors = ""; //what?? this should be array()
这应该是这样的:
$result = mysql_query("select * FROM color") or die(mysql_error());
$colors = array();
while($colorrec = mysql_fetch_array($result)){
$colors[$colorrec['ID']] = array();
$colors[$colorrec['ID']]['Desc'] = $colorrec['Description'];
$colors[$colorrec['ID']]['Hex'] = $colorrec['HexCode'];
}
然后你可以这样做:
echo "color code WHT";
echo "description ".$colors['WHT']['Desc'];
echo "Hex Code ".$colors['WHT']['Hex'];
答案 1 :(得分:0)
走这条路肯定没问题。此外,如果您迷失在阵列中,只需快速print_r($array)
,它就会为您输出结构。
答案 2 :(得分:0)
尝试:
$result = mysql_query("select * FROM color") or die(mysql_error());
$colors = array();
while($colorrec = mysql_fetch_array($result)){
$colors[$colorrec['ID']] = array(
$colorrec['Description'] ,
$colorrec['HexCode'] );
}
echo "color code WHT";
echo "description ".$colors['WHT'][0];
echo "Hex Code ".$colors['WHT'][1];
答案 3 :(得分:0)
class Color { $description =""; $hexcode = ""; $someOther=""; } $colors = array(); $result = mysql_query("select * FROM color") or die(mysql_error()); while($colorrec = mysql_fetch_array($result)) { $color = new Color(); $id=$colorrec['HexCode']; $color->description = $colorrec['Description']; $color->hexCode = $colorrec['HexCode']; $colors[$id] = $color; } echo $color['ID']->description; echo $color['ID']->hexCode;
答案 4 :(得分:0)
我这样用:
$numfields = mysql_num_fields($result);
while($red = mysql_fetch_array($result)){
for ($j=0; $j<$numfields; $j++ ) {
$field_name = mysql_field_name($result, $j);
//create Matrix
$datapull[$i][$field_name] = $red[$field_name];
}
$i++;
}
mysql_free_result($result);
var_dump($datapull);
这更通用,更难搜索,它应该在类方法或函数中使用,因此您传递SQL并始终期望与结果相同的格式。