如何将此字符串转换为数组?

时间:2012-02-03 03:24:17

标签: php arrays

  

可能重复:
  PHP - split String in Key/Value pairs

嘿,专家如何将此字符串转换为可用的数组?

FNAME = first_name的,L-NAME =姓氏,电话= PHONE_NUMBER,street1 =地址,城市=城市,州=州,邮政编码=拉链,载体=载体

7 个答案:

答案 0 :(得分:2)

array_map(function ($i) { return explode('=', $i); }, explode(',', $string))

答案 1 :(得分:1)

某些事情 -     foreach(split($ long_str,',')为$ pair){        $ pair_arr = split($ pair,'=');        $ map [$ pair [0]] = $ pair [1];     }

我确定语法已关闭,但它应该会给你一个想法。

答案 2 :(得分:0)

$arr = array();

$pieces = explode(",", $str);
foreach($pieces as $piece)
{
    list($key, $value) = explode('=', $piece);
    $arr[$key] = $value;
}

答案 3 :(得分:0)

$res = array();
for ($i in explode(',', $input)) {
    $parts = explode('=', $i);
    $res[$parts[0]] = $parts[1];
}

答案 4 :(得分:0)

试试这个:

$chunks = explode(',', $string);
$arr = array();
foreach($chunks as $set)
{
    $kv = explode('=',$set);
    $arr[$kv[0]] = $kv[1];
}

那会给你:

$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';

这是explode上的php手册页。

答案 5 :(得分:0)

$ 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($结果);

答案 6 :(得分:0)

/**
 * 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]);
}