0

我有这样的场景:

$data = "A,B,C=>fruit'\n'D,E,F=>veggie'\n'A,D=>mix"
$rules = array_map('trim', explode('\n', $data));
$i = 1;
foreach ($rules as $rule) {
   $letter_group."_".$i = array_map('trim', explode('=>', $rule));
   $letter.$i = array_map('trim', explode(',', $letter_group."_".$i[0]));
   $group.$i = array_map('trim', explode(',', $letter_group."_".$i[1]));
   $i++;
   var_dump($letter.$i);
   var_dump($group.$i);
}

但这不起作用。如何获得这些输出?

$letter1 = array('A','B','C');
$letter2 = array('D','E','F');
$letter3 = array('A','D');
$group1 = array('fruit');
$group2 = array('veggie');
$group3 = array('mix');
4

1 回答 1

0

我同意这些评论,您应该尝试将您的值放入一个数组中(为此 +1)。我认为这就是你想要的:

<?php
$data = "A,B,C=>fruit'\n'D,E,F=>veggie'\n'A,D=>mix";
$data=str_replace("'","",$data);//you don't need the single quotes in there
$rules = explode("\n", $data);
$array=array();
foreach ($rules as $rule) {
    $ar=explode("=>",$rule);
    $array[$ar[1]]=explode(",",$ar[0]);
}
print_r($array);
?>

这打印出来:

Array
(
[fruit] => Array
    (
        [0] => A
        [1] => B
        [2] => C
    )

[veggie] => Array
    (
        [0] => D
        [1] => E
        [2] => F
    )

[mix] => Array
    (
        [0] => A
        [1] => D
    )

)

从以下问题编辑:

虽然我建议将其存储在上面的多用途数组中,但如果您必须将它们放在单独的变量中,您可以从上面构建的数组中分配变量:

$letter1=$ar['fruit']
$letter2=$ar['veggie'];
$letter3=$ar['mix'];
//etc ....

我可以问一下,为什么您需要在单个变量中使用这些?

于 2012-10-23T05:47:14.813 回答