好的。降低你对这一项的n00b标准。现在回头。
我有三个文件:
- index.php(主页)
- project.php(每个项目的模板页面)
- project-data.php(保存索引和项目的项目数据)
我有一个带有项目列表的函数。
项目数据.php
<?php
function getDataForPageRender($id)
{
if (empty($home)) {
$id = $_GET["id"];
}
$returnArray = array();
if($id == 1)
{
$returnArray['title'] = 'Project Snoop';
} else if($id == 2)
{
$returnArray['title'] = 'Project Biggie';
} else if($id ==3)
{
$returnArray['title'] = 'Project Tupac';
}
return $returnArray;
}
?>
(实际上有大约 25 个项目,而不仅仅是 3 个。因此,我渴望将这些东西自动化。但以我目前的知识水平,没有足够的项目让我想要创建一个数据库。)
这是我的每个项目页面,效果非常好。每个项目的 URL 格式为“project.php?id=3”。
project.php
<?php
include 'project-data.php';
$dataForPage = getDataForPageRender($id);
$id = $_GET["id"];
$title = $dataForPage['title'];
?>
<html>
<head></head>
<body>
<h1><?php echo $title; ?></h1>
</body>
</html>
现在,在我的 index.php 页面上,我想回显每个项目标题。像这样:
窥探计划
大项目
图帕克计划
我已经用无数种方法尝试了 foreach 循环,但没有成功。
index.php
<?php
include 'project-data.php';
foreach (array(1,2,3) as &$value) {
$home = "true"; // I know, ghetto. I'm trying lots of different things quickly.
$id = $value;
getDataForPageRender();
$dataForPage = getDataForPageRender($id);
echo $dataForPage['title'];
echo "<br>";
}
?>
我似乎无法回应index.php 上每个项目的标题。这看似简单,但每一次的页面刷新都给我的心灵带来挫败感。
提前致谢:)
最佳答案
您在 project-data.php
中使用 $home
,它可能存在于 index.php
中,但不存在于函数getDataForPageRender
。
您需要遵循 DI 并将 $home
传递到函数中,如下所示:
function getDataForPageRender($id, $home) //<-- added home
{
if (empty($home)) {
$id = $_GET["id"];
}
/* rest of code */
然后,您需要将 $home
传递给您的函数。
$dataForPage = getDataForPageRender($id, $home); //which you set as $home = "true";
这应该会让你的代码运行,但我想指出一些可能会导致警告的事情,但你可能禁用了警告。
foreach (array(1,2,3) as &$value) {
&$value
,&是通过引用传递的,但由于数组是匿名的,因此无法更改该数组的值,只需将其保留在 foreach (array (1,2,3) as $value) {
,不带 &
。
而且我不知道为什么您要在没有任何参数的情况下运行 getDataForPageRender();
。
关于php - 如何从函数内部回显有关每个项目的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26447440/