Jump to content

combining a key array and a value array


michaellunsford

Recommended Posts

I've been digging through the manual and I just can't find what I'm looking for ??? I know it's in there somewhere. I already have my own slow function to do this, but I was hoping one of you guys (or gals) could remind me how to do it with PHP's built in stuff.

CSV file (tab separated). The top line contains the column names, each consecutive row contains data. I'd like to use the top row for the array key when I grab the other rows. I'm currently using fopen() and fgets() to explode() each line and loop through each key and value from the separate arrays and create a third array that's formatted properly. I'm not loading the entire file into memory -- just working one line at a time.

What function or combination of functions does this already?

Thanks!
Link to comment
https://forums.phpfreaks.com/topic/34064-combining-a-key-array-and-a-value-array/
Share on other sites

If I am understanding you correctly I would suggest the following:

When grabbing the first line, explode it into an array and save to a variable (ex. $keys).

Then create a loop to grab each succesive line and explode into an array (ex. $values)

Then add the $values array, using the $keys array, to a results array (ex. $results) using array_combine()

$results[] = array_combine($keys, $values);
Kind of the long way around, I could probably combine a few steps

[code]<?php
$keys=explode("\t",$line);
$myarray=array_combine($keys,explode("\t",fgets($fil)));
?>[/code]

only one problem... Still running PHP4 on the server :(
try
[code]
<?php
function array_combine4 ($a, $b)  {
    $res = array();
    $v = current($b);
    foreach ($a as $k) {
        $res[$k] = $v;
        $v = next($b);
    }
    return $res;
}
?>
[/code]
To ease your future migration process, you might want to do this: (it's Barand's function, just renamed and wrapped in an if). This way when you upgrade to a version that has array_combine, then it should work seamlessly.

[code=php:0]
if (!function_exists('array_combine')) {
    function array_combine ($a, $b)  {
        $res = array();
        $v = current($b);
        foreach ($a as $k) {
            $res[$k] = $v;
            $v = next($b);
        }
        return $res;
    }
}
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.