Возьмите средние результаты х, на основе ключевых результатов в элегантной форме

У меня есть набор продуктов. В зависимости от состояния страницы, я показываю один продукт, а затем до 4 других продуктов. Результирующий набор продуктов может быть любого размера больше, чем 5 продуктов. Я хочу ВСЕГДА показать 5 товаров. Если возможно, я хочу показать 2 продукта ниже (в наборе результатов) и 2 продукта выше.

Примеры:

Если будет 10 результатов, а ключевой продукт — 5. Я хочу показать 3,4,5,6,7.

Если будет 10 результатов, а ключевой продукт — 9. Я хочу показать 6,7,8,9,10.

Если будет 10 результатов, а ключевой продукт — 1. Я хочу показать 1,2,3,4,5.

Прямо сейчас я использую min () и max () и некоторые «IF», ​​чтобы понять это, и это занимает смешное количество строк кода, когда есть элегантное решение, я просто не нахожу его !
пример массива результатов, приведенный ниже

$similar_products = array(
array(
"id" => 1,
"title" => "Product One"),
array(
"id" => 2,
"title" => "Product Two"),
array(
"id" => 3,
"title" => "Product Three"),
array(
"id" => 4,
"title" => "Product Four"),
array(
"id" => 5,
"title" => "Product Five"),
array(
"id" => 6,
"title" => "Product Six"),
array(
"id" => 7,
"title" => "Product Seven"),
array(
"id" => 8,
"title" => "Product Eight"),
array(
"id" => 9,
"title" => "Product Nine"),
array(
"id" => 10,
"title" => "Product Ten")
);
$i = 8; //change this value to test different key product array positions
$arrOut = array();
$floor = 0;
if($i <= 1) { //the key product is either in the first or second position in the array
$floor = 0;
$arrOut[] = $similar_products[0];
$arrOut[] = $similar_products[1];
$arrOut[] = $similar_products[2];
$arrOut[] = $similar_products[3];
$arrOut[] = $similar_products[4];
} elseif((count($similar_products)-1)-$i <= 1) {  //the key product is either in the last or second to last in the array
$floor = count($similar_products)-5;
$arrOut[] = $similar_products[count($similar_products)-5];
$arrOut[] = $similar_products[count($similar_products)-4];
$arrOut[] = $similar_products[count($similar_products)-3];
$arrOut[] = $similar_products[count($similar_products)-2];
$arrOut[] = $similar_products[count($similar_products)-1];
} else {  //otherwise, just grab two above and two below
$floor = $i-2;
$arrOut[] = $similar_products[$i-2];
$arrOut[] = $similar_products[$i-1];
$arrOut[] = $similar_products[$i];
$arrOut[] = $similar_products[$i+1];
$arrOut[] = $similar_products[$i+2];
}
$x = $floor;  //set x, our counter, to the floor (floor = the very first output postion)
foreach($arrOut as $ao) {
if($x == $i) {  //current key product
echo "<strong>" . $ao['id'] . ":" . $ao['title'] . "</strong><hr/>";
} else {  //other NON key products
echo $ao['id'] . ":" . $ao['title'] . "<hr/>";
}
$x++;
}

0

Решение

Если вы хотите, вы можете удалить переменную config, немного сжать ее и сделать ее 1-строчной 😉
Я не очень хорош в этом, так что, возможно, есть более эффективные и / или более короткие варианты.

// Set array index, starts with 0
// If you need to find with specific ID, just find the index by the ID
$primaryIndex = 4;// change this number to test

// How many extra items to show
// Must be divisible by 2
$extraToShow = 4;

// Find total items available - 1 to work with array indexes
$maxIndex = count($similar_products) - 1;

// Find the slice start
$low = min($maxIndex - $extraToShow, max(0, $primaryIndex - 1 - $extraToShow / 2));

// Slice to needed
$items = array_slice($similar_products, $low, $extraToShow + 1);

var_dump($items);
1

Другие решения

<?php
// example code
$productKey = 7;
$resultsShown = 5;
$totalResults = 10;//num_rows()?
$limit = floor($resultsShown/2);
$min = $limit;
$max = $totalResults - $limit;
if($productKey<=$min){
for($i = 1;$i<=$resultsShown; $i++){
//Display result
echo $i;
}
}
else if($productKey>$max){
for( $i = $totalResults - $resultsShown+1; $i <=$totalResults;$i++){
//Display result
echo $i;
}}
else{
for( $i = $productKey - $limit; $i<=$productKey + $limit; $i++){
//Display result
echo $i;
}
}

У меня не было возможности провести тестирование, так как я работаю на мобильном телефоне, но я думаю, что самый простой способ решить эту проблему, давая вам возможность изменить эти фиксированные ограничения в будущем, не изящно, но не может увидеть, что у вас есть на момент для сравнения!

0

По вопросам рекламы [email protected]