$Towns = ['Plovdiv', '40', 'Pernik', '20', 'Vidin', '8', 'Sliven', '44', 'Plovdiv', '1', 'Vidin', '7', 'Chirpan', '0'];
$emptyTown = [];
$emptyIncome = [];
$calculated = [];
$rowCount = 0;
foreach ($Towns as $town){
$rowCount++;
$rowCount2++;
if($rowCount % 2){
$emptyTown[$town] = '';
}else{
$emptyIncome[$town] = '';
}
}
This is how far I managed to get. My idea is to get every town's name and save it in array as a key and every number is a town INCOME. So I need something like
Plovdiv => 40
Pernik => 20
Vidin => 8
Sliven => 44
Plovdiv => 1
Vidin => 7
Chirpan => 0
I have no clue I can't explain the way to do it to myself. The best Idea I came up with is to save them in two arrays and then merge them somehow. Can you guys explain me some ways that you may do it?
Use a for
loop that increments by 2.
$TownIncomes = [];
for ($i = 0; $i < count($Towns); $i += 2) {
$TownIncomes[$Towns[$i]] = $Towns[$i+1];
}
using foreach
check whether $key%2
equals 0
foreach($Towns as $key => $value){
if($key%2 == 0){
$new[$value] = $Towns[$key + 1];
}
}
$data = ['Plovdiv', '40', 'Pernik', '20', 'Vidin', '8', 'Sliven', '44',
'Plovdiv', '1', 'Vidin', '7', 'Chirpan', '0'];
$towns = [];
$counter = 0;
foreach($data as $index => $value) {
if($counter == 0){
$towns[$value] = $data[$index + 1];
$counter++;
}
$counter = 0;
}
print_r($towns); //Array ( [Plovdiv] => 1 [Pernik] => 20 [Vidin] => 7
[Sliven] => 44 [Chirpan] => 0 )
I've refactored it slightly... however, indexes cannot have the same value, so the duplicated Vidin and Plovdiv overwrite the initial ones.
Have a play with this and you should be able to get it working...
$towns[$value][] = $data[$index + 1]; <---- doing something like that
Will allow you to add multple values to the town if they have multiple incomes, but will need some refactoring of the code to work.
Is your data in that format and cannot be changed? ie. 'town', 'value', 'town', 'value' ... ?