Skip to content

Instantly share code, notes, and snippets.

@richjenks
Last active June 4, 2019 01:25
Show Gist options
  • Save richjenks/2ba64ecd375269b5c969 to your computer and use it in GitHub Desktop.
Save richjenks/2ba64ecd375269b5c969 to your computer and use it in GitHub Desktop.
Find the value at an intersection of a CSV file when given column and row headings
<?
/**
* 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
*/
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 'csv-intersection.php';
echo intersect('data.csv', 'Bar', 'Fizz');
// 2
echo intersect('data.csv', 'Foor', 'Buzz');
// 3
echo intersect('data.csv', 'Foo', 'Bar');
// null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment