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.
Snippets of code and tricks that would otherwise be forgotten. Useful for me, hopefully for you too.
Tuesday, July 31, 2012
Tuesday, July 10, 2012
ajaxload.info
This site is a fast and free way to create ajax loading icons like this:
ajaxload.info
Custom colors, color or transparent backgrounds, many styles, free. Check it out
ajaxload.info
Custom colors, color or transparent backgrounds, many styles, free. Check it out
Subscribe to:
Posts (Atom)