[英]Can't grasp function concept in php code
So I have an index.php file that has data.php (array list of different types of items): 所以我有一个index.php文件,其中包含data.php(不同类型的项的数组列表):
$catalog[304] = [
"title" => "The Very Thought of You",
"img" => "img/media/nat_king_cole.jpg",
"genre" => "Jaz",
"format" => "MP3",
"year" => 2008,
"category" => "Music",
"artist" => "Nat King Cole"
]; //and so on ->
I also have a function.php file that hold this function: 我也有一个拥有此功能的function.php文件:
function get_item_html($id, $item) {
$output =
"<li><a href='#'><img src='"
. $item["img"] . "' alt='"
. $item["title"] . "' />"
. "<p> View Details </p>"
. "</a></li>";
return $output;
And then the index.php which have both files included at the top: 然后是index.php,其中两个文件都位于顶部:
<ul class="items">
$random = array_rand($catalog, 4);
foreach ($random as $id) {
echo get_item_html($id, $catalog[$id]);
}
What I can't grasp is the "$catalog[$id]". 我无法理解的是“ $ catalog [$ id]”。 It seems like it should return the catalog ID, not the key within the catalog ID. 似乎应该返回目录ID,而不是目录ID中的键。 But apparently the code is valid, because it does work. 但是显然,该代码是有效的,因为它确实有效。 It's just that I can't understand why. 只是我不明白为什么。
I know that I am way off in this but if someone could explain it to me I would be super grateful. 我知道我在这方面还很遥远,但是如果有人可以向我解释一下,我将非常感激。
Thanks! 谢谢!
$catalog[$id] simply returns an array with id=$id from your data.php file and your get_item_html method utilises img and title values of this array and generates some html. $ catalog [$ id]只是从data.php文件中返回一个id = $ id的数组,而get_item_html方法利用此数组的img和title值并生成一些html。 So if your random generator picked lets say 304 then your output would be: 因此,如果您选择的随机生成器是304,那么您的输出将是:
<li><a href='#'><img src='img/media/nat_king_cole.jpg' alt='The Very Thought of You' />
<p> View Details</p>
</a>
</li>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.