foreach循环中增加的唯一变量

时间:2012-10-23 05:12:56

标签: php

我有这样的场景:

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

1 个答案:

答案 0 :(得分: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 ....

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