Created
April 23, 2012 22:53
-
-
Save bigdawggi/2474388 to your computer and use it in GitHub Desktop.
String Arrays to PHP arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
echo '<pre>'; | |
class string_array_parser { | |
function parse_string($key, $value) { | |
// no limit, no empty values in returned array | |
$splits = preg_split('[\[|\]]', $key, -1, PREG_SPLIT_NO_EMPTY); | |
// Get the first element, that will be the name of the actual meta key | |
$meta_key_name = array_shift($splits); | |
// Get the last element, this will be the key for the value | |
$last_element_name = array_pop($splits); | |
// Set us if not present, but do the check so we don't override preivously set values | |
if (!isset($this->$meta_key_name)) { | |
$this->$meta_key_name = array(); | |
} | |
// Magic happens here. Basically it pushes an empty array as a specific key to the last-iterated item of an array. | |
$latest_item = &$this->$meta_key_name; | |
foreach ($splits as $v) { | |
if (!isset($latest_item[$v])) { | |
// PHP 5.2 throws warning about array-ness of $latest_item[$v], but still works | |
@array_push($latest_item[$v], array()); | |
} | |
$latest_item = &$latest_item[$v]; | |
} | |
$latest_item[$last_element_name] = $value; | |
} | |
} | |
$a = new string_array_parser; | |
$a->parse_string('contact[facebook]', 'http://facebook.com'); | |
$a->parse_string('contact[twitter]', 'http://twitter.com'); | |
$a->parse_string('office[1][address1]', '211 S Main St'); | |
$a->parse_string('office[1][city]', 'Smalltown'); | |
$a->parse_string('office[2][address1]', '8125 E 130TH PL'); | |
$a->parse_string('office[2][city]', 'Bigtown'); | |
$a->parse_string('contact[website]', 'http://example.com'); | |
print_r($a); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment