Skip to content

Instantly share code, notes, and snippets.

@kmuenkel
Last active May 15, 2020 16:59
Show Gist options
  • Save kmuenkel/43bb39ed34488eca0d71e650596e9546 to your computer and use it in GitHub Desktop.
Save kmuenkel/43bb39ed34488eca0d71e650596e9546 to your computer and use it in GitHub Desktop.
<?php
/**
* @param array[] $matrix
* @param string[] $fields
* @return array[]
*/
public function tilt(array $matrix, array $fields = array())
{
$topKeys = array_keys($matrix);
$nestedKeys = $fields ?: array_keys((array)current($matrix));
$numResults = count($matrix);
$matrix = array_pad($matrix, 2, array_fill_keys($nestedKeys, null)); //Empty sets still need to result in arrays
array_unshift($matrix, null); //Sending null as the array_map() closure is what tilts the matrix
$matrix = call_user_func_array('array_map', $matrix);
$matrix = $nestedKeys ? array_combine($nestedKeys, $matrix) : array(); //Preserve and move the keys
array_walk($matrix, function (array &$column) use ($numResults, $topKeys) {
$column = array_slice($column, 0, $numResults); //Prune off the placeholders, if any were needed
$column = array_combine($topKeys, $column);
});
return $matrix;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment