[英]Most efficient way to loop through data with PHP
我目前正在重构一个网站,并且遇到了一组链接,这些链接看起来都一样,但是有一些不同的变量/文本。
我了解循环以及所有内容,这绝对是必需的,但是我不确定如何最好地处理变化的各种数据。
HTML如下:
<div class="featuredSide" style="border-color:#fff">
<h3 style="font-size: 20px; margin-bottom: 12px;">$sectionName</h3>
<img src="images/$imageName.jpg" width="50" height="60" style="float: left; margin: 4px 8px 16px 0px; border: 2px solid #fff;" />
<h4 style="font-size: 11px;">$author</h4>
<p class="lineAboveCol" style="clear: both; margin-bottom: 0px;"><a href="resources.php?section=$section">Click here for more information</a></p>
</div>
我已放入变量来替换将要更改的数据(这些当前均以HTML格式完成)。
因此,遍历这些数据的最佳方法是什么,我想到了使用简单的数组,但从长远来看,我认为这并不是特别容易维护的方法。 是否有一个我遗失的简单解决方案,或者甚至值得在MySQL表中设置此数据并直接从那里提取?
谢谢。
可以做到..
<?php
$theVars[0]['sectionName'] = "section name 1";
$theVars[0]['section'] = "section 1";
$theVars[0]['author'] = "author 1";
$theVars[1]['sectionName'] = "section name 2";
$theVars[1]['section'] = "section 2";
$theVars[1]['author'] = "author 2";
$theVars[2]['sectionName'] = "section name 3";
$theVars[2]['section'] = "section 3";
$theVars[2]['author'] = "author 3";
$htmlStr = "";
for($i=0;$i<=2;$i++){
$htmlStr .= '<div class="featuredSide" style="border-color:#fff">
<h3 style="font-size: 20px; margin-bottom: 12px;">'.$theVars[$i]['sectionName'].'</h3>
<img src="images/$imageName.jpg" width="50" height="60" style="float: left; margin: 4px 8px 16px 0px; border: 2px solid #fff;" />
<h4 style="font-size: 11px;">'.$theVars[$i]['author'].'</h4>
<p class="lineAboveCol" style="clear: both; margin-bottom: 0px;"><a href="resources.php?section='.$theVars[$i]['section'].'">Click here for more information</a></p>
</div>';
}
echo $htmlStr;
?>
我在球场上吗?
我将从数组开始:
$links = array(
'section1' => array(
'section' => '...',
'sectioName' => '...',
'imageName' => '...',
'author' => '...',
// 'text' => 'Click here for more information',
),
);
然后运行一个循环。 它很容易适应,可以保留不同的表示形式和数据,并且将来可以将其移至MySQL或其他持久层,也许还提供了一个后端接口以允许维护人员编辑部分。
如果各节之间需要一些变化,则可以将其拉入数组(或MySQL中的列)的键中。
您也可以从外部提供HTML并运行特殊标签的preg_replace,例如{{ author }}
被$currentSection['author']
的内容替换,依此类推。 这也很容易移植到任何模板引擎。
我将使用php array进行此特定操作,但将该数组保存在其他文件中,因此很容易更新/上传
我将使用的代码将类似于
section.values.php
$sections = array(
'Section 1' => 'Author 1',
'Section 2' => 'Author 2',
);
然后在html / php页面上:
<?php
include("section.values.php"); //or any file name
foreach($sections as $sectionName => $author){
echo '<div class="featuredSide" style="border-color:#fff">
<h3 style="font-size: 20px; margin-bottom: 12px;">' . $sectionName . '</h3>
<img src="images/$imageName.jpg" width="50" height="60" style="float: left; margin: 4px 8px 16px 0px; border: 2px solid #fff;" />
<h4 style="font-size: 11px;">' . $author . '</h4>
<p class="lineAboveCol" style="clear: both; margin-bottom: 0px;"><a href="resources.php?section=' . $section . '">Click here for more information</a></p>
</div>';
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.