Q:

Write a PHP program which reads a list of pairs of a word and a page number, and prints the word and a list of the corresponding page numbers

0

Write a PHP program which reads a list of pairs of a word and a page number, and prints the word and a list of the corresponding page numbers.
The number of pairs of a word and a page number is less than or equal to 1000. A word never appear in a page more than once. The words should be printed in alphabetical order and the page numbers should be printed in ascending order.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?php
$page = array();
while($line = fgets(STDIN)){
    list($a, $b) = explode(" ", trim($line));
    if(!isset($page[$a])){
        $page[$a] = array();
    }
    $page[$a][] = $b;
} 
ksort($page);
echo "The word and a list of the corresponding page numbers:\n";
foreach($page as $word => $arr){
    sort($arr, SORT_NUMERIC);
    echo $word."\n";
    echo implode($arr, " ")."\n";
}

?>

Sample Input:
apple 5
banana 6

Sample Output:

The word and a list of the corresponding page numbers:
apple
5
banana
6

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now