How do I inject keys into an array using specific ranges?
So, I have a code that outputs the following:
$test = array('test1.txt' => '1 June 2015',
'test2.txt' => '1 June 2015',
'test3.txt' => '1 June 2015',
'test4.txt' => '1 June 2015',
'test5.txt' => '1 June 2015');
But instead of 5 files, there are hundreds. How would I go about this so that I can determine the date issued based on the ie line number
If file is 1-5 (first 5 files), then date = "June 1, 2015". If file is 6-8 (next 2 files), then date = "June 5, 2015. Etc. How can I do this?
+3
source to share
2 answers
You can try this -
$date = "1 June 2015"; // The initial date
$fileNum = array(5, 2, 3); // The number of files to be considered
$total = array_sum($fileNum); // Total number of files
$array = array(); // Array to be filled
$j = 1; // The number for increment
foreach($fileNum as $num) {
$i = 1; // The number to compare the file numbers
while($i <= $num) {
$array['test' . $j . '.txt'] = $date; // Store the values
$j++;
$i++;
}
$date = date('j F Y', strtotime('+ 1 DAY', strtotime($date))); // Increment the date
}
var_dump($array);
Output
array(10) {
["test1.txt"]=>
string(11) "1 June 2015"
["test2.txt"]=>
string(11) "1 June 2015"
["test3.txt"]=>
string(11) "1 June 2015"
["test4.txt"]=>
string(11) "1 June 2015"
["test5.txt"]=>
string(11) "1 June 2015"
["test6.txt"]=>
string(11) "2 June 2015"
["test7.txt"]=>
string(11) "2 June 2015"
["test8.txt"]=>
string(11) "3 June 2015"
["test9.txt"]=>
string(11) "3 June 2015"
["test10.txt"]=>
string(11) "3 June 2015"
}
Update
$fileNum = array(5 => "1 June 2015", 2 => "2 June 2015", 3 => "3 June 2015"); // Set the array with file number and corresponding dates
$total = array_sum($fileNum);
$array = array();
$j = 1;
foreach($fileNum as $num => $date) {
$i = 1;
while($i <= $num) {
$array['test' . $j . '.txt'] = $date;
$j++;
$i++;
}
}
+1
source to share
try it
$numberOfFiles = 100;
//$startDate = '1 June 2015';
$startDate = '1 June 2015';
for($i=1;$i<=$numberOfFiles;$i++)
{
if($i%5==0)
{
$test['test'.$i.'.txt'] = $startDate;
$startDate = date('j F Y',strtotime($startDate.' + 5 days'));
}
else
{
$test['test'.$i.'.txt'] = $startDate;
}
}
print_r($test);
Updated on demand. Note. You must determine the date by the file number.
$numberOfFiles = 50;
//$startDate = '1 June 2015';
for($i=1;$i<=$numberOfFiles;$i++)
{
if($i<=5)
{
$startDate ='1 June 2015';
$test['test'.$i.'.txt'] = $startDate;
}
elseif((5<$i)&&($i<=8))
{
$startDate ='2 June 2015';
$test['test'.$i.'.txt'] = $startDate;
}
elseif((8<$i)&&($i<=50))
{
$startDate ='11 June 2015';
$test['test'.$i.'.txt'] = $startDate;
}
else
{
// Define the date value if does not match above criterian
}
}
print_r($test);
0
source to share