我正试图从数据库中获取记录,并单击一个链接,它传递参数以获取所需的url。但是当我点击链接时,我得到以下错误:
警告:第31行/home/next/public_html/cms/index.php中foreach()的参数无效
使用的代码是:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once('includes/class-query.php');
if ( !empty ( $_GET ) ) {
if ( !empty ( $_GET['p'] ) ) {
$post = $_GET['p'];
}
if ( !empty ( $_GET['cat'] ) ) {
$cat = $_GET['cat'];
}
}
if ( empty ( $post ) && empty ( $cat ) ) {
$posts_array = $query->all_posts();
} elseif ( !empty ( $post ) ) {
$posts_array = $query->post($post);
} elseif ( !empty ( $cat ) ) {
echo 'cat';
} ?>
<html>
<head>
<title></title>
</head>
<body>
<?php foreach ( $posts_array as $post ) : ?>
<div class="post">
<h1><a href="?p=<?php echo $post->ID; ?>"><?php echo $post->post_title; ?></a></h1>
<p><?php echo $post->post_content; ?></p>
</div>
<?php endforeach; ?>
</body>
</html>
这段代码的失败情况是定义了$cat。再加上@Mohammad Imran Ashraf的建议,如果你写这样的东西,错误就会消失。
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once('includes/class-query.php');
if ( !empty ( $_GET ) ) {
if ( !empty ( $_GET['p'] ) ) {
$post = $_GET['p'];
}
if ( !empty ( $_GET['cat'] ) ) {
$cat = $_GET['cat'];
}
}
if ( empty ( $post ) && empty ( $cat ) ) {
$posts_array = $query->all_posts();
} elseif ( !empty ( $post ) ) {
$posts_array = $query->post($post);
} elseif ( !empty ( $cat ) ) {
$posts_array = array();
} ?>
<html>
<head>
<title></title>
</head>
<body>
<?php foreach ( $posts_array as $post ) : ?>
<div class="post">
<h1><a href="?p=<?php echo $post->ID; ?>"><?php echo $post->post_title; ?></a></h1>
<p><?php echo $post->post_content; ?></p>
</div>
<?php endforeach; ?>
</body>
</html>
或
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once('includes/class-query.php');
if ( !empty ( $_GET ) ) {
if ( !empty ( $_GET['p'] ) ) {
$post = $_GET['p'];
}
if ( !empty ( $_GET['cat'] ) ) {
$cat = $_GET['cat'];
}
}
$posts_array = array();
if ( empty ( $post ) && empty ( $cat ) ) {
$posts_array = $query->all_posts();
} elseif ( !empty ( $post ) ) {
$posts_array = $query->post($post);
} elseif ( !empty ( $cat ) ) {
echo "cat";
} ?>
<html>
<head>
<title></title>
</head>
<body>
<?php foreach ( $posts_array as $post ) : ?>
<div class="post">
<h1><a href="?p=<?php echo $post->ID; ?>"><?php echo $post->post_title; ?></a></h1>
<p><?php echo $post->post_content; ?></p>
</div>
<?php endforeach; ?>
</body>
</html>
这两种解决方案中的任何一种都可以。希望能有所帮助。根本原因是未初始化的阵列$posts_array
。因此,要么首先初始化它,要么在else子句中为它赋值。
您需要在最后一个else中传递一个数组,因为您在另外两个if中返回一个数组,并且使用该数组进行foreach循环。
修改此代码
if ( empty ( $post ) && empty ( $cat ) ) {
$posts_array = $query->all_posts();
} elseif ( !empty ( $post ) ) {
$posts_array = $query->post($post);
} elseif ( !empty ( $cat ) ) {
//Change this line and pass an array instead of echo something
echo 'cat';
}