在php中创建动态数组

时间:2012-05-21 06:55:39

标签: php arrays variables dynamic

我在文本文件中有以下记录,需要提取该记录表单文本文件并将它们视为单独的数组变量

r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)由管道分隔(|)

我需要将其表示为数组单独使用,如下所示

$r1= Array
(
[0] => 1
[1] => 2
[2] => 3
)

$r2=Array
(
[0] => 4
[1] => 5
[2] => 6
)

我不知道怎么做,是不是可以用PHP?

6 个答案:

答案 0 :(得分:1)

只是一个简单的正则表达式来分解字符串,然后在每个组上爆炸:

if (preg_match_all('#(\w+)=\(([\d,]*)\)#', $s, $matches)) {
    foreach ($matches[2] as $i => $groups) {
        $group_name = $matches[1][$i];
        $$group_name = array_map('intval', explode(',', $groups));
    }
}

print_r($r1);
print_r($r3);
print_r($rn);

答案 1 :(得分:0)

$data = "r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";

$arr = explode("|", $data);

$finArray = array();

foreach($arr as $key=>$value)
{
    $single = explode('(', $value);
    $finArray[] = explode(',', str_replace(')', '', $single[1]));
}

print_r($finArray);

答案 2 :(得分:0)

您可以使用Eval

//Assuming  you can pull the content from text file using fread

$temp = "r1=(1,2,3)|r2=(4,5,6)";
$temp=str_replace("=","=array",$temp);
$split=explode("|",$temp);
echo "<pre>";
foreach($split as $k=>$v){
      $v="$".$v.";";
      //Evaluate a string as PHP code .i.e You will get r1,r2 as a variable now which is array
      eval($v);
}

print_r($r1);
print_r($r2);

答案 3 :(得分:0)

此代码可以帮助您: -

  <?php
    $file = "/tmp/file1.txt"; // this is your file path
    $f = fopen($file, "r");
    while ( $line = fgets($f, 1000) ) {
    print $line;

    $a=explode('|',$line);
    print_r($a);  // I have explode based on | for you...

foreach($a as $key=>$value)
{
    print_r($value);
}

FCLOSE($文件);         }         ?&GT;

“” 或 “”

$a="r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";

$a=explode('|',$a);
print_r($a);

答案 4 :(得分:0)

可以完成:

$string="r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";
$string=str_repla("r1=","",$string);
$yourArray=explode('|', $string);

答案 5 :(得分:0)

    <?php
$file = "file.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
$str = $line;
}
$str1 = explode("|",$str);
foreach($str1 as $temp) {
    $str2 = explode("=",$temp);
    $data[$str2[0]] = explode(",",trim($str2[1],"()"));
}
echo '<pre>';
print_r($data);
echo '</pre>';
?>

这将完成你的工作。