phparraysforeacharray-combine

PHP combine_array produces false when element count is the same


Apologies if this question is close to others. I have tried every solution to accomplish something simple with nothing but failure. :-(

I want the keys from array one to be assigned as keys to array two.

$demos_keys = array_keys($demos);

//$c = array_combine($demos_keys, $csvdata); produces "FALSE"
//$c = $demos_keys +  $csvdata; simply adds the arrays but doesn't assign keys

So then I tried to loop through each element to assign the keys manually - to no avail! 

foreach ($csvdata as $row){
     for($i = 0; $i<count($demo_keys); $i++) {
        $csvdata[$demo_keys[$i]]=$row[$i];
     } 
}

demos_keys: lastname":"lastname","email":"email","d1":"phone","d2":"status"

csvdata: "Dryer,fdryer@email.com,Backfield,North\r","Harris,fharris@email.com,Corp,South\r",etc.

I feel the csvdata array is wonky somehow. Every thing say it is an array with about 1000 rows, but the carriage return at the end of the last element is troubling me. I thought I'd deal with it later.

What else can I try!? Thank you all for any contributions!


Solution

  • It looks like each row of your CSV data has not been parsed into separate variables (are you reading it from a file using fgets or file instead of fgetcsv?). So you need to split it before you can combine it with the keys from $demos_keys. Something like this should work:

    $demos_keys = array("lastname","email","d1","d2");
    $csvdata = array("Dryer,fdryer@email.com,Backfield,North\r","Harris,fharris@email.com,Corp,South\r");
    
    $result = array();
    foreach ($csvdata as $row) {
        $data = explode(',', trim($row));
        $result[] = array_combine($demos_keys, $data);
    }
    print_r($result);
    

    Output:

    Array
    (
        [0] => Array
            (
                [lastname] => Dryer
                [email] => fdryer@email.com
                [d1] => Backfield
                [d2] => North
            )
        [1] => Array
            (
                [lastname] => Harris
                [email] => fharris@email.com
                [d1] => Corp
                [d2] => South
            )
    )
    

    Demo on 3v4l.org