我正在使用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个值
答案 0 :(得分:2)
你在这里:
$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
var分配到array_splice
结果中。
答案 1 :(得分:1)
<?php
// Get the last 6 entries of an array...
$arr = array(
1,
2,
3,
4,
5,
6,
7,
8
);
$entries = array_splice($arr, -6);
// returns [3, 4, 5, 6, 7, 8]
}
答案 2 :(得分:0)
$maxResultLength = 6;
$someArray = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d','e','f','g','h'];
$startIndex = (count($someArray) >= $maxResultLength) ? count($someArray) - $maxResultLength : 0;
$lastSixElements = array_slice($someArray, $startIndex, $maxResultLength);
或
$maxResultLength = 6;
$someArray = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d','e','f','g','h'];
$lastSixElements = array_splice($someArray, -6);