爆炸数据/将其转换为PHP数组

时间:2011-09-26 19:57:22

标签: php arrays

我的数据变量如下:

 canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4

我需要它转换为一个应该看起来如下的数组:

$arr = array(
"canv" => array("2", "3", "4", "5"),
"canp" => array("2", "3", "4"),
"canpr" => array("2", "3", "4"),
"canpp" => array("2", "3", "4"),
"all" => array("2", "3", "4")
);

你能帮助我吗?

4 个答案:

答案 0 :(得分:1)

以下应该可以解决问题:

$data = "canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4";
$items = explode(":::", $data);
$arr = array();
foreach($items as $item) {
    $item = explode(" = ", $item);
    $arr[$item[0]] = explode(",", $item[1]);
}

答案 1 :(得分:1)

$data = "canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4";
$result = array();
foreach (explode(':::', $data) as $line) {
    list($part1, $part2) = explode(' = ', $line);
    $result[$part1] = explode(',', $part2);
}

答案 2 :(得分:0)

$orig_str = 'canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4';

$parts = explode(':::', $orig_str);

$data = array()
foreach($parts as $key => $subparts) {
    $data[$key] = explode(',', $subparts);
}

答案 3 :(得分:0)

我会尝试这样的事情:这没有经过测试,请尝试print_r进行调试

$string = "canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4";

$pieces = explode(':::',$string);
$result = array();
foreach($pieces AS $piece)
{
   $tmp = explode(' = ',$piece);
   $result[$tmp[0]] = explode(',',$tmp[1]);
}