作为一名实习生,我意识到我花了大量的时间在PHP中从sql查询构建和操纵表。我当前的方法是使用两个foreach循环:
foreach($query as $record){
foreach($record as $field => $value){
*Things that need to be done on each field-value pair*
}
*Things that need to be done on each row*
}有没有更好的方法来做这件事?
此外,我倾向于将数据打包为~分隔的列表,并将其存储在服务器中,这是不是一个糟糕的做法?
我宁愿把一些代码放上来审查,但我不想冒着暴露公司代码内部的风险。
发布于 2012-12-06 00:24:11
Foreach循环是遍历数据的最佳方式。如果你想让你的代码更美观一点,试着使用三元版本
<?php foreach($query as $record) : ?>
<?php foreach($record as $field => $value) : ?>
*Things that need to be done on each field-value pair*
<?php endforeach; ?>
*Things that need to be done on each row*
<?php endforeach; ?>另外,就像在上面的注释中提到的,在db中存储分离的数据时,您会失去很多功能。如果必须这样做,可以尝试存储序列化对象,而不是分隔字符串。您可以通过多种方式操作对象,例如json_encode()和json_decode()
$myArray = array();
$myArray['User1']['book'] = 'Pride and Prejudice';
$myArray['User1']['favorites'] = 'Water skiing';
$myArray['User2']['book'] = 'Mansfield Park';
$myArray['User2']['favorites'] = array('skateboarding', 'surfing', 'running');
$myArray['description'] = 'Things people like.';
echo '<pre>';
print_r(json_encode($myArray)); //This will convert your array to a string for the db
echo '</pre>';
echo '<pre>';
$myArrayString = json_encode($myArray);
print_r(json_decode($myArrayString)); //This will convert the db string to an object for manipulation
echo '</pre>';发布于 2012-12-06 00:27:43
没有内置的方法可以从查询结果生成HTML表。如果您发现自己一遍又一遍地编写这样的代码,那么创建一个可重用的类或库将是一个很好的选择。例如:
$table = new HTMLTable();
$table->setData($data);
echo $table->toHTML();上面不是工作代码,只是一个如何创建可重用代码的示例,而不是多次重复相同的表构建代码。
发布于 2012-12-06 01:51:15
我倾向于使用一个带有mysql_fetch_..函数的while循环。但从本质上讲,它与你所做的是一样的。
$query = 'SELECT
stuff
FROM
table';
if ($query = mysql_query($query)) {
while ($row = mysql_fetch_assoc($query)) {
foreach ($row as $key => $value) {
/* Things that need to be done on each field-value pair */
}
/* Things that need to be done on each row */
}
}至于~分隔的列表。我强烈建议将数据保存在单独的DB字段中,而不是像这样打包。只需为每个这样的包创建一个新表。
https://stackoverflow.com/questions/13727335
复制相似问题