Tuesday, July 31, 2012

Referencing an array within an object with a $variable property name (PHP)

Whew. This took some research and about thirty minutes of banging my face against the keyboard...

In a Drupal module I'm developing I'm allowing the user to upload a .csv file, then I'm parsing the contents of each row into a property of an object. A brief example of the code looks like:

    $handle = fopen($file, "r");
   
    $csv_content = new stdClass();
    while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {           
            $csv_content->$data[0] = array(
                'first_name' => $data[0],
                'hobbies' => array() // *** the new array
            );
     }

     fclose($handle);

I created an empty array for each row's 'hobbies' property, in hopes that I would later be able to stuff values into this array. I quickly found this to be a lot more difficult that I expected.  I eventually realized it was a matter of the syntax I was using, specifically a problem with using a variable as the name of an object property.

It turns out that :  $csv_content->$data[0]['hobbies'] was not giving me access to the new array created under the 'hobbies' property of $csv_content->$data[0]  ( I think because PHP is interpreting $data[0]['hobbies'] to be the property name, rather than ['hobbies'] being an array within the $data[0] property )

THE SOLUTION:
To force PHP to recognize $data[0] as the property name, WRAP IT IN CURLY BRACES!

$csv_content->{$data[0]}['hobbies']  does the trick!

I hope someone finds this helpful. I had never run across this problem before.

No comments:

Post a Comment