OK. I am working in a PHP
project.
and I have some categorized data in my database -
For example- I have data of Three Categories.
Category 1
Category 2
Category 3
Categories could be changed. Like 2,3,4,5 etc.
And i have facility to show a limit of data.
Ex. Lets say Admin want to show only 9 Records
So now we have three categories and x limit (which is 9 according to example). and best thing is that-
I need to show N numbers of records from each category and total X records.
Here N numbers is for each Category. So it will look like this:
N1 + N2 + N3 = X (limit ex. 9)
N1 from Category1
N2 from Category2
N3 from Category3
So basically i have formulated it like this -
NumberOfRecordPerCategory = X (limit) / N (Number of Categories)
But it is actually working if i set the limit multiple of 3 like 6,9,12 etc.
So my Question is-
How do i manage the total records according to limit (X) -
1. if Admin set the limit which is not multiple by 3 like 8,10,11, etc.
2. if Admin change the number of category Like 2 or 4, then how could i manage this?
Please give some idea about this. and please let me know if Question is not clear.
What I would choose for your requirement is ceil (round fractions up). If there is some fractions because the number is not multiple by 3, for example 11 with 3 categories, then have the limitation of 4,4,3 for each category. This could be done by having two limit values: limit of total, limit per category. Here's my suggestion for your needs (code) :
<?php
/*
$data = array (
"category1" => array (1,2,3,4,5),
"category2" => array (10,20,30,40,50),
"category3" => array (100,200,300,400,500),
);
*/
$limit = 11; // given by the admin
$number_of_categories = count($data);
$limit_per_category = ceil ( $limit / $number_of_categories ); // ceil (11 / 3) = 4
$cnt = 0; // tracking the total number of retrieved data.
foreach ($data as $row) {
$cnt_category = 0;
foreach ($row as $item) {
echo $item . "
"; // print the first N (NumberOfRecordPerCategory) data
$cnt_category++;
$cnt++;
if ($cnt >= $limit) break; // exit the loop
if ($cnt_category >= $limit_per_category) break; // move to next category
}
if ($cnt >= $limit) break; // exit the loop
}