Skip to content

Instantly share code, notes, and snippets.

@aprimc
Created October 21, 2015 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aprimc/72850c92ee2ebfa12e31 to your computer and use it in GitHub Desktop.
Save aprimc/72850c92ee2ebfa12e31 to your computer and use it in GitHub Desktop.
<?php
/*
Extract the data represented as an array of columns and represent it as an
array of rows.
Assert that the data in all non-empty columns is of the same length.
Represent empty columns with an array of $zeros.
*/
function columns_to_rows($wanted_columns, $data_as_columns, $zero) {
// find the length of non-empty columns
// check if wanted columns are missing or empty
// crash if non-empty columns are of a different length
$length = null;
$some_columns_are_missing = false;
foreach ($wanted_columns as $col) {
if (!isset($data_as_columns[$col])) {
$some_columns_are_missing = true;
} else {
if ($length === null && isset($data_as_columns[$col]) && count($data_as_columns[$col]) > 0) {
$length = count($data_as_columns[$col]);
} else {
if ($length != count($data_as_columns[$col])) {
throw new LogicException('Columns must be of the same length');
}
}
}
}
// return early if no data
if ($length === null) {
return array();
}
// represent missing data with $zero
if ($some_columns_are_missing) {
$zeros = array_fill(0, $length, $zero);
}
// use array_map(null, col[1], col[2]...) to zip arrays
$args_for_array_map = array(null);
foreach ($wanted_columns as $col) {
$args_for_array_map[] = isset($data_as_columns[$col]) ? $data_as_columns[$col] : $zeros;
}
$data_as_rows = call_user_func_array('array_map', $args_for_array_map);
// handle quirk
if (count($wanted_columns) == 1) {
$t = array();
foreach ($data_as_rows as $value) {
$t[] = array($value);
}
$data_as_rows = $t;
}
return $data_as_rows;
}
# TEST
$wanted_columns = array('quuxes', 'foos', 'bars', 'bazzes');
#$wanted_columns = array('foos');
$data_as_columns = array(
'foos' => array(5, 3, 9),
'bars' => array(0, 1, 2),
'noise' => "such baz"
);
print_r($wanted_columns);
echo "\n";
print_r($data_as_columns);
echo "\n";
print_r(columns_to_rows($wanted_columns, $data_as_columns, 0));
echo "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment