我正在使用PHP数组存储产品ID的逗号分隔值,然后依次使用它们来显示最近看到的产品。
实现如下:
$product_data = array();
$array_ids_a_display = array();
$check_status = array();
$array_check= array();
$_COOKIE['Pr'] = [1,2,3,4,5,6,7,8]
然后我正在存储的字符串的最后一点
$array_check = explode(',',substr($_COOKIE['IdProduto'],0,-1));
现在,我检查产品是否启用,然后将它们存储到另一个阵列中
foreach($array_check as $id_a_checar){
$check_status = $this->model->getProduct($id_a_checar);
if($check_status['status']){ // If status is 1
$array_ids_a_display[$contprods++] = $id_a_checar;
}
}
if($s['limit']>count($array_ids_a_display)){
//If the number of valid products < number of products of module
$s['limit'] = count($array_ids_a_display);
//will show,then reconfigures the number of products that will show
}
}
其中
$s['limit']
来自后端,我们说6
以限制产品数量。现在,我将反转阵列以首先获得最新访问的产品,例如
$last_ended = array_reverse($array_ids_a_display);
array_splice($last_ended,0,(int)$s['limit']);
foreach ($last_ended as $result) {
$product_data[$result] = $this->product->getProduct($result);
}
现在出现了问题,因为我在$ product_data数组中仅获得3个产品,但将获得6个产品。
我希望
array_splice
有问题,因为如果我要评论array_splice,那么我将所有存储产品都存储在cookie中。MySQL查询工作得很好。
请咨询如何从数组中获取最新的6个值
最佳答案
这个给你:
$last_ended = array(1, 2, 3, 4, 5, 6, 7, 8);
$last_ended = array_reverse($last_ended);
//here is what you missed:
$last_ended = array_splice($last_ended, 0, 6);
print_r($last_ended);
//returns Array ( [0] => 8 [1] => 7 [2] => 6 [3] => 5 [4] => 4 [5] => 3 )
您需要将
$last_ended
变量分配给array_splice
结果。