Skip to content

Instantly share code, notes, and snippets.

@richjenks
Last active February 12, 2017 13:12
Show Gist options
  • Save richjenks/997a27750687ab06268eb126336bccb0 to your computer and use it in GitHub Desktop.
Save richjenks/997a27750687ab06268eb126336bccb0 to your computer and use it in GitHub Desktop.
Finds a value in a CSV file based on its column and row header

Intersect CSV

Finds a value in a CSV file based on its column and row header

Usage

mixed intersect ( string $filename , mixed $column , mixed $row )

Parameters

  • filename
    • Path to CSV file
  • column
    • Column header as it appears in CSV file
  • row
    • Row header as it appears in CSV file

Return Values

Returns value at intersection on success (casted, e.g. could be string or float depending on value) or NULL on failure.

Notes

  • Assumes that cells in the first row are row headers and cells in the first column are column headers
  • The first cell of the first row will be ignored and attempts to search by it will return NULL, hence it is empty in the example above
<?php
/**
* Finds the value of an intersection of a CSV file
* when given column and row headings
*
* @param string $file Path to CSV file
* @param string $column Column heading to search by
* @param string $row Row heading to search by
*
* @return mixed Value at intersection or NULL if not found
*/
function intersect($file, $column, $row) {
// All cells will be strings
$column = (string) $column;
$row = (string) $row;
// Get table
$table = array_map('str_getcsv', file($file));
// Get headings and flip so values match row keys
$headings = array_shift($table);
array_shift($headings); // First is empty!
$headings = array_flip($headings);
// Move row headings to array keys
foreach ($table as $key => $value) $rows[array_shift($value)] = $value;
// Get column key, if exists
if (!isset($headings[$column])) return null;
$key = $headings[$column];
// Get intersection value, if exists
if (!isset($rows[$row][$key])) return null;
$value = $rows[$row][$key];
// Attempt to cast to a sensible type
if (in_array(strtolower($value), ['true', 'false'])) $value = (bool) $value;
if (is_numeric($value)) $value = $value+0;
return $value;
}
,foo,bar
fizz,1,2
buzz,3,4
<?php
require 'intersect-csv.php';
echo intersect('data.csv', 'foo', 'buzz');
// 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment