mysql_fetch_array and array keys
This code works:
$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);
}
}
And this does not, probably doing something wrong in the 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);
}
}
Nothing is shown if post is more than 1. Anyone know a way to solve this problem?
mysql_fetch_array()
fetches one single row, which, in your case, contains exactly one column.
You should either query all rows from the result set at once (which I don't know how that works), or you should do this:
$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 as well have adjusted the boundaries: if you are interested in the range $i-2
to $i+2
, you only should run from 2
to end-2
.
The select statement should be rewritten so as to return only the values you're looking for. One way to do this is with a UNION
of two selects, one returning lesser object IDs and one returning greater. You should also make use of WordPress's wpdb
class. For one thing, a site admin may change the table prefix from "wp_" to something else; $wpdb->term_relationships
will give the correct name for the table.
$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);
This also has the advantage of working when there are less than two terms relationships before or after the center (the object with id $post
).
精彩评论