此代码有效:
$row = array(5,6,89,97,101);
$found = array();
$post = 89;
$count_row = count($row);
for($i = 0; $i < $count_row; $i++){
if($row[$i]==$post){
$found[] = $row[$i-2];
$found[] = $row[$i-1];
$found[] = $row[$i];
$found[] = $row[$i+1];
$found[] = $row[$i+2];
var_dump($found);
}
}
这不是,可能在mysql_fetch_array中做错了;
$found = array();
$q = "SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id='$term_tax_id'";
$rs = mysql_query($q) or die(mysql_error());
$row = mysql_fetch_array($rs, MYSQL_NUM);
$count_row = count($row);
for($i = 0; $i < $count_row; $i++){
print_r($row);
if($row[$i]==$post){
$found[] = $row[$i-2];
$found[] = $row[$i-1];
$found[] = $row[$i];
$found[] = $row[$i+1];
$found[] = $row[$i+2];
var_dump($found);
}
}
如果帖子超过1,则不会显示任何内容。 有人知道解决这个问题的方法吗?
答案 0 :(得分:4)
mysql_fetch_array()
获取一行,在您的情况下,只包含一列。
您应该立即查询结果集中的所有行(我不知道它是如何工作的),或者您应该这样做:
$q = "SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id='$term_tax_id'";
$rs = mysql_query($q) or die(mysql_error());
$data = array();
while ($row = mysql_fetch_array($rs, MYSQL_NUM)) {
$data[] = $row[0];
}
for($i = 2; $i < count($data) - 2; $i++){ // adjusted boundaries
if($data[$i]==$post){
$found[] = $data[$i-2];
$found[] = $data[$i-1];
$found[] = $data[$i];
$found[] = $data[$i+1];
$found[] = $data[$i+2];
var_dump($found);
}
}
}
我也调整了界限:如果您对范围$i-2
到$i+2
感兴趣,则只能从2
到end-2
。
答案 1 :(得分:1)
应该重写select语句,以便只返回您要查找的值。一种方法是使用UNION
两个选项,一个返回较小的对象ID,一个返回更大。您还应该使用WordPress的wpdb
类。首先,网站管理员可以将表格前缀从“wp_”更改为其他内容; $wpdb->term_relationships
将为表格提供正确的名称。
$statement = $wpdb->prepare(
" (SELECT object_id
FROM $wpdb->term_relationships
WHERE term_taxonomy_id= %d
AND object_id <= %d
ORDER BY object_id DESC
LIMIT 3)
UNION
(SELECT object_id
FROM $wpdb->term_relationships
WHERE term_taxonomy_id= %d
AND object_id > %d
ORDER BY object_id ASC
LIMIT 2)
ORDER BY object_id", $term_tax_id, $post, $term_tax_id, $post);
$found = $wpdb->get_results($statement);
当中心之前或之后(ID为$post
的对象)的关系少于两个时,这也有一个优势。