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
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);
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.