', $rank); // If the pair of items are not blank if ($pair[0] != "" && $pair[1] != "") { // Add each item to the items array $items[$pair[0]] = true; $items[$pair[1]] = true; // Add the pair to the adjacency matrix $matrix[$pair[0]][$pair[1]]++; } } // 5. How to sort associate array by index/key ksort($matrix); // 5. Iterate over outer array assoicative array, i.e., the array of rows foreach ($matrix as $rowkey=>$row) { // Make a table echo ''; echo ''; echo ''; // Sort each row from highest to lowest arsort($row); // Iterate over columns to print keys foreach ($row as $colkey=>$value) { echo ''; } echo ''; // Print the row key echo ''; echo ''; // Iterate over rows to print values foreach ($row as $colkey=>$value) { echo ''; } // Finish up the table echo ''; echo '
Row>Column'.$colkey.'
'.$rowkey.''.$value.'
'; echo '
'; } // Limit on the depth of recursion $limit = 3; // Recursive "ranking" algorithm function getsum($m, $name, $level) { // Use the global variable so they don't have to be copied global $not_visited; global $matrix; global $limit; // No point in going too deep into the tree if ($level >= $limit) { return 0; } else { // Mark self as visited to prevent loops $not_visited[$name] = false; // Calculate the sum of the "wins" for $name at current level $sum = 0; // Iterate over row $m foreach ($m as $key=>$value) { // To prevent loops to other visited nodes if ($not_visited[$key]) { // Call get sum on all of items we "beat" $sum += $value + getsum($matrix[$key], $key, $level+1)/2 ; } } // Unmark self as visited $not_visited[$name] = true; return $sum; } } // For storing each item's score $scores = array(); //Iterate over items to get score foreach ($items as $key=>$value) { $not_visited = $items; $score = getsum($matrix[$key], $key, 0); $scores[$key] = $score; } // Sort the scores arsort($scores); // Print the scores echo '
    '; foreach ($scores as $key=>$value) { echo '
  1. '.$key." score is ". $value . '
  2. '; } echo '
'; echo json_encode($scores); ?>