explode two-item-list in array as key=>value

人盡茶涼 提交于 2019-12-03 03:13:15

Use explode(), you can use a regexp for it, but it's simple enough without the overhead.

$data = array();
foreach (explode("\n", $dataString) as $cLine) {
    list ($cKey, $cValue) = explode(':', $cLine, 2);
    $data[$cKey] = $cValue;
}

As mentioned in comments, if data is coming from a Windows/DOS environment it may well have CRLF newlines, adding the following line before the foreach() would resolve that.

$dataString = str_replace("\r", "", $dataString); // remove possible \r characters

The alternative with regexp can be quite pleasant using preg_match_all() and array_combine():

$matches = array();
preg_match_all('/^(.+?):(.+)$/m', $dataString, $matches);
$data = array_combine($matches[1], $matches[2]);
Myo

Try this

$value = '1|a,2|b,3|c,4|d';
$temp = explode (',',$value);
foreach ($temp as $pair) 
{
    list ($k,$v) = explode ('|',$pair);
    $pairs[$k] = $v;
}

print_r($pairs);

explode first on line break. Prolly \n

Then explode each of the resulting array's items on : and set a new array to that key/value.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!