Blog

Quick Code: csv to associative array


So I was trying out stackoverflow when I saw this crappy associative serialization problem
Almost similar questions are repeated. I am updating and fetching string from database for different issues. lets say after fetching value from database one of my variable $str looks like one of the below $str = "1:1,2:1,3:2,5:6"; or $str = "1|1,2|1,3|2,5|6"; or $str = "1=1,2=1,3=2,5=6"; how can I convert anyone or almost different string to an associative array in PHP thanks in advance. I tried for an answer but didnt find anything similar. code i tried to make it an associative array
So here's the code I ended up with: /** * Converts CSV to associative array * * @param string $str * */ function csv2associative_array($str) {   $csv_items = preg_split('/\s*\,\s*/',$str);   $items = array();   foreach ($csv_items as $x => $csv_item) {      list($key,$value) = preg_split('/\W/',$csv_item,2);      if ($key && $value) {         $items[$key] = $value;      }      else {         trigger_error("keys/values not found for item #$x");      }   }   return $items; }

Comments (0)


Add a Comment





Allowed tags: <b><i><br>Add a new comment:


A Few Accomplishments

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer non. Adipiscing cubilia elementum integer. Integer eu ante ornare amet commetus.

Possibly broke spacetime

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer adipiscing ornare amet.

Terraformed a small moon

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer adipiscing ornare amet.

Snapped dark matter in the wild

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer adipiscing ornare amet.

Contact Me

Integer eu ante ornare amet commetus vestibulum blandit integer in curae ac faucibus integer non. Adipiscing cubilia elementum integer. Integer eu ante ornare amet commetus.