Possible Duplicate:
PHP - split String in Key/Value pairs
Hey experts how would I turn this string into a usable array?
fname=first_name,lname=last_name,phone=phone_number,street1=address,city=city,state=state,zip=zip,carrier=carrier
Possible Duplicate:
PHP - split String in Key/Value pairs
Hey experts how would I turn this string into a usable array?
fname=first_name,lname=last_name,phone=phone_number,street1=address,city=city,state=state,zip=zip,carrier=carrier
array_map(function ($i) { return explode('=', $i); }, explode(',', $string))
something along the lines of-- foreach(split($long_str, ',') as $pair) { $pair_arr = split($pair, '='); $map[$pair[0]] = $pair[1]; }
I'm sure the syntax is off, but it should give you the idea.
$arr = array();
$pieces = explode(",", $str);
foreach($pieces as $piece)
{
list($key, $value) = explode('=', $piece);
$arr[$key] = $value;
}
$res = array();
for ($i in explode(',', $input)) {
$parts = explode('=', $i);
$res[$parts[0]] = $parts[1];
}
Try this:
$chunks = explode(',', $string);
$arr = array();
foreach($chunks as $set)
{
$kv = explode('=',$set);
$arr[$kv[0]] = $kv[1];
}
That will give you:
$arr['fname'] = 'first_name';
$arr['lname'] = 'last_name';
$arr['phone'] = 'phone_number';
$arr['street1'] = 'address';
$arr['city'] = 'city';
$arr['state'] = 'state';
$arr['zip'] = 'zip';
$arr['carrier'] = 'carrier';
Here's php manual page on explode.
$str = "fname=first_name,lname=last_name,phone=phone_number,street1=address,city=city,state=state,zip=zip,carrier=carrier";
parse_str(str_replace(",", "&", $str), $result);
var_dump($result);
/**
* Converts a string to an associative array.
*
* Usage:
*
* echo strToAssocArray("k=v,k2=v2", "=", ",");
* // outputs array('k' => 'v', 'k2' => 'v2')
*
* @param string $str the string
* @param string $keyValueSep the separator between key and value
* @param string $recordSep the record separator
* @return array the resulting associative array
*/
function strToAssocArray($str, $keyValueSep, $recordSep)
{
$sep1 = preg_quote($keyValueSep);
$sep2 = preg_quote($recordSep);
$regex = '/(.*?)' . $sep1 . '(.*?)(?:' . $sep2 . '|$)/';
preg_match_all($regex, $str, $matches);
return array_combine($matches[1], $matches[2]);
}