水果案例:
在一个水果网页上,点击水果动态跳转到另一页面。
fruit.php文件:::
<?php
header('content-type:text/html;charset=utf-8');
//1.第一步、读取fruit.txt
$str = file_get_contents('./fruit.txt');
// print_r($str);
//2.使用explode转换成数组
$arr = explode("\n",$str);
// print_r($arr);
//3.使用foreach+explode转换成二维数组
foreach($arr as $key => $value){
//创建新得空数组接收value值;
$array[] = explode("|",$value);
}
// print_r($array);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="header">
传智网上水果超市
</div>
<div class="container">
<p>
<a href="javascript:;">水果</a>
<a href="javascript:;">干果</a>
<a href="javascript:;">蔬菜</a>
</p>
<ul>
<?php
// 循环创建li元素
foreach($array as $key => $value){ ?>
<li>
<img src="<?php echo $value[1]?>" alt="">
<!-- 点击链接跳转到 ‘detail.php’文件下; -->
<a href="detail.php?id=<?php echo $value[0]?>"><?php echo $value[2]?></a>
</li>
<?php }?>
</ul>
</div>
<div class="footer">
传智播客 版权所有
</div>
</body>
</html>
detail.php文件::
<?php
header('content-type:text/html;charset=utf-8');
//接收a链接跳转过来的id值;
if(isset($_GET['id'])){
$id = $_GET['id'];
// print_r($id);
}else{};
// 同fruit.php
// 读取fruit.txt文件;
$str = file_get_contents('./fruit.txt');
// print_r($str);
// 使用explode转换成数组
$arr = explode("\n",$str);
// print_r($arr);
// 循环$arr
foreach($arr as $key => $value){
$array[] = explode("|",$value);
}
// print_r($array);
// 循环数组$array
foreach ($array as $key => $value) {
// 让每一个$array第零个值与‘fruit.php’文件下的a链接跳转过来的id值;
if($value[0] == $id){
// $id值 是否等于当前数组$array第零个相等
// 如果相等 就变量等于当前数组$value;
$data = $value;
break;
}
}
// print_r($data);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./style.css">
<style>
.container ul > li {
float: none;
width: 100%;
text-align: center;
}
.container ul > li img {
width: auto;
}
</style>
</head>
<body>
<div class="header">
传智网上水果超市
</div>
<div class="container">
<p>
<a href="#">水果</a>
<a href="#">干果</a>
<a href="#">蔬菜</a>
</p>
<ul>
<li>
<!-- 把$data里的值插入相应的目录下 -->
<img src= "<?php echo $data[1]?>" alt="">
<p>这是 <?php echo $data[2]?>的详情图</p>
</li>
</ul>
</div>
<div class="footer">
传智播客 版权所有
</div>
</body>
</html>
fruit.txt文件::
1|img/banana1.jpg|香蕉2|img/apple1.jpg|苹果
3|img/orange1.jpg|橘子
4|img/pineapple1.jpg|菠萝
5|img/mango1.jpg|芒果
6|img/grape1.jpg|葡萄
7|img/pomelo1.jpg|柚子
8|img/pawpaw1.jpg|木瓜
9|img/kivi1.jpg|猕猴桃
10|img/persimmon1.jpg|柿子
11|img/lemon1.jpg|柠檬
12|img/pomegranate1.jpg|石榴
13|img/pear1.jpg|梨
14|img/strawberry1.jpg|草莓
15|img/blueberry1.jpg|蓝莓
16|img/waxberry1.jpg|杨莓
17|img/peach1.jpg|桃
18|img/coconut1.jpg|椰子
19|img/apricot1.jpg|杏
20|img/cherry1.jpg|樱桃