note 106318 added to function.array-combine
| From: | dejiakala at gmail dot com | Date: | Thu, 27 Oct 2011 10:32:50 +0000 |
| Subject: | note 106318 added to function.array-combine | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-184162@lists.php.net to get a copy of this message | ||
I needed to read CSV files into associative arrays with column headers as keys. Then I ran into a
problem when you have empty columns at the end of a row because array_combine returns false if both
arrays don't have the same number of elements. This function based on quecoder at gmail's
combine_arr() below allowed me to pad either array or not when parsing my CSVs to arrays.
$a is the array of header columns and $b is an array of the current row retrieved with fgetcsv()
<?php
function array_combine_special($a, $b, $pad = TRUE) {
$acount = count($a);
$bcount = count($b);
// more elements in $a than $b but we don't want to pad either
if (!$pad) {
$size = ($acount > $bcount) ? $bcount : $acount;
$a = array_slice($a, 0, $size);
$b = array_slice($b, 0, $size);
} else {
// more headers than row fields
if ($acount > $bcount) {
$more = $acount - $bcount;
// how many fields are we missing at the end of the second array?
// Add empty strings to ensure arrays $a and $b have same number of elements
$more = $acount - $bcount;
for($i = 0; $i < $more; $i++) {
$b[] = "";
}
// more fields than headers
} else if ($acount < $bcount) {
$more = $bcount - $acount;
// fewer elements in the first array, add extra keys
for($i = 0; $i < $more; $i++) {
$key = 'extra_field_0' . $i;
$a[] = $key;
}
}
}
return array_combine($a, $b);
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 83.244.244.5
----
Manual Page -- http://www.php.net/manual/en/function.array-combine.php
Edit -- https://master.php.net/note/edit/106318
Del: integrated -- https://master.php.net/note/delete/106318/integrated
Del: useless -- https://master.php.net/note/delete/106318/useless
Del: bad code -- https://master.php.net/note/delete/106318/bad+code
Del: spam -- https://master.php.net/note/delete/106318/spam
Del: non-english -- https://master.php.net/note/delete/106318/non-english
Del: in docs -- https://master.php.net/note/delete/106318/in+docs
Del: other reasons-- https://master.php.net/note/delete/106318
Reject -- https://master.php.net/note/reject/106318
Search -- https://master.php.net/manage/user-notes.php