I have created the following nested for loop in python - the idea is to take a int value for hours e.g 6 and then create an array of values from 1-6
hours = 6
hoursArray = [6]
convertHours = [] #Creating empty list
for i in hoursArray:
for j in range(i-1): #This will iterate till the value in list - 1
convertHours.append(j 1) #Appending values in new list
hoursList = convertHours hoursArray
print(hoursList) #adding both the lists
output [1, 2, 3, 4, 5, 6]
Here is my attempt with php - I'm confused about the inner loop and how to do "for j in range(i-1)" in php also in php i should be getting the max value of the array into the range of the outer loop for($i = 0; $i <= $hoursArray-1; $i )
- again i'm not sure how to do this so i put in the int value $hours
to test it.
<?php
$hours = 6;
$hoursArray = [$hours];
$convertHours =[];
for($i = 0; $i <= $hours-1; $i ) {
for($j = 0; $j <= $i-1; $j ) {
$convertHours = [$j 1];
$hoursList = array_merge($convertHours, $hoursArray);
}
}
var_dump($hoursList);
print_r($hoursList);
?>
Output array(2) { [0]=> int(5) [1]=> int(6) } Array ( [0] => 5 [1] => 6 )
Any help appreciated!!
CodePudding user response:
Your problem is in the line of $convertHours = [$j 1];
. This way you overwrite the value that was in $convertHours before. You have to write $convertHours[] = $j 1;
This way there will be a new value appended to the array. Alternatevly you can also use array_push($convertHours, $j 1)
CodePudding user response:
array_merge
merges the 2 arrays based on their key
$convertHours = [$j 1];
Is equivalent to:
$convertHours = [0 => $j 1];
So when you merge them they all have the same key
but differents values
.
You should do something like that I think:
for($j = 0; $j <= $i-1; $j ) { $hoursArray[] = $j 1; }
This append to your array
the values $j 1
then ultimately you could use sort
to sort your array