Перейти к содержанию

Разное на PHP

Функции для работы с постраничным выводом.

Разбиваем массив элементов, постранично.

/**
 * The resulting list is in the form of an array. ret[pages][items] = value
 * 
 * @author Maksyutin Dmitriy
 * @param $list array List of elements
 * @param $first_page_items integer Show items on first page
 * @param $mid_page_items integer Show item count on middle pages
 * @param $last_page_item_send integer Show number of items on last page no more
 * @return array The resulting list is in the form of an array. ret[pages][items] = value
 */
function priceToPage(array $list, int $first_page_items = 7, int $mid_page_items = 10, int $last_page_item_send = 8): array
{
    $first_page_array = [];

    $total_items = count($list);

    if ($total_items > $first_page_items) {
        $first_page_array[1] = array_slice($list, 0, $first_page_items);
        $list = array_slice($list, $first_page_items);
    } else {
        $first_page_array[1] = $list;
        return $first_page_array;
    }

    $current_page = 2;
    $total_items = count($list);

    for ($current_item = 1; $current_item <= $total_items; $current_item++) {
        $first_page_array[$current_page][] = $list[$current_item - 1];
        if (($current_item) % $mid_page_items == 0 and ($current_item + $first_page_items) != $total_items) {
            $current_page++;
        }
    }

    $res = $list = $first_page_array;
    $last_page = count($list);
    $last_page_item = $list[$last_page];
    $last_page_item_count = count($list[$last_page]);
    if ($last_page_item_count > $last_page_item_send) {
        $res[$last_page] = array_slice($last_page_item, 0, $last_page_item_send);
        $res[] = array_slice($last_page_item, $last_page_item_send);
    }
    return $res;
}