John Davidson

arraylist - PHP inserting text from a file into array

0 comments
Message:


I have a text file with cities and population and a php program that should read the text file and insert the text into array while taking into account that the city should be key and the population is value of the array and the program has to sort the array by the value and to print its keys and values in table format.


Example data:


Tokyo   39105000
Jakarta 35362000
Delhi 31870000
Manila 23971000
Sao Paulo 22495000
Seoul 22394000
Mumbai 22186000
Shanghai 22118000
Mexico City 21505000
Guangzhou 21489000

This is the code:


    <?php
$fileHandler = fopen("Info_array.txt", "rb");
$data = [];

while (!feof($fileHandler) ) {
// read file row
$row = fgets($fileHandler);

$index = count($data);

// explode array by space
$data[$index] = explode(' ', $row);

// explode data[$index][0] by '.', then insert into array in index 0 & 1
array_splice($data[$index], 0, 1, explode('.', $data[$index][0]));
}

// sort array by array index 1
usort($data, function ($prev, $next) {
if ($prev[1] == $next[1]) {
return 0;
}

return ($prev[1] < $next[1]) ? -1 : 1;
});

fclose($fileHandler);
?>

<table class="heavyTable">
<thead>
<tr>
<th>City</th>
<th>Population</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $item): ?>
<tr>
<td><?= $item[0] . '.' . $item[1] ?></td>
<td><?= $item[2] ?></td>
<td><?= $item[1] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

I currently get error:


Warning: Undefined array key 1 in C:\xampp\htdocs\phpexercise.php on line 20

Warning: Undefined array key 1 in C:\xampp\htdocs\phpexercise.php on line 20

Warning: Undefined array key 1 in C:\xampp\htdocs\phpexercise.php on line 20

Warning: Undefined array key 1 in C:\xampp\htdocs\phpexercise.php on line 20

Any advices on how to do this will be very much appreciated, i'm struggling from a few days now.



My Answer:
// Read the text file
$file = fopen("cities.txt", "r");
$data = array();

// Insert text into array
while (!feof($file)) {
$line = fgets($file);
$city_population = explode(" ", $line);
$city = $city_population[0];
$population = intval($city_population[1]);
$data[$city] = $population;
}

// Sort the array by value
arsort($data);

// Print keys and values in table format
echo "";
echo "";
foreach ($data as $city => $population) {
echo "";
}
echo "
CityPopulation
$city$population
";
fclose($file);
?>

Rate this post

5 of 5 based on 9165 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us