从动态变量PHP创建数组

时间:2013-04-18 02:10:35

标签: php arrays associative-array

我正在使用以下代码。每次从文件中准备好一行时,我需要将它添加到一个关联数组

$fp = fopen("printers.txt", "r"); // Open ptinters.txt to be read by fgets()


        // While not end of the file, read a line and store it in $printer
        while (!feof($fp)) {
            $printer = fgets($fp, 256);


            // Split the line of text into three sections and store them into
            // variables named $pName $printerType and $numPages.
            $tempArray = explode(":", $printer); 

            $pName = $tempArray[0];
            $printerType = $tempArray[1];
            $numPages = $tempArray[2];


            //Create 2 arrays. First stores $pName and $printerType 
            // second stores $pName and $numPages 


        }; // Close while !feof $fp loop.

fclose($fp); // close $fp file pointer stream.

2 个答案:

答案 0 :(得分:1)

以下代码创建array1 = [name] => printertype和array2 = [name] => numpages

$array1 = array();
$array2 = array();
$fp = fopen("printers.txt", "r"); // Open ptinters.txt to be read by fgets()
while (!feof($fp)) {
    $printer = fgets($fp, 256);
    $tempArray = explode(":", $printer); 
    $array1[$tempArray[0]] = $tempArray[1];
    $array2[$tempArray[0]] = $tempArray[2];
}
fclose($fp);

如果您有重复的打印机名称,请执行以下操作,为您提供array1 array{[0] => array([name] => printertype),...[n] => array([name] => printertype)}和array2 array{[0] => array([name] => numpages),...[n] => array([name] => numpages)}

$i = 0;
while (!feof($fp)) {
    $printer = fgets($fp, 256);
    $tempArray = explode(":", $printer); 
    $array1[$i] = array($tempArray[0] => $tempArray[1]);
    $array2[$i] = array($tempArray[0] => $tempArray[2]);
    $i++;
}

根据您的意见:

$pType = array();
$pages = array();
$fp = fopen("printers.txt", "r"); // Open ptinters.txt to be read by fgets()
while (!feof($fp)) {
    $printer = fgets($fp, 256);
    $tempArray = explode(":", $printer);

    $pName = $tempArray[0];
    $printerType = $tempArray[1];
    $numPages = $tempArray[2];

    $pType[$pName] = $printerType;
    $pages[$pName] = $numPages;
}
fclose($fp);

答案 1 :(得分:0)

$types = $nums = array();

$fp = fopen('printers.txt', 'r');

while (!feof($fp)) {
    $printer = fgets($fp, 256);

    list($name, $type, $pages) = explode(':', $printer); 

    $types[] = compact('name', 'type');
    $nums[]  = compact('name', 'pages');
}

fclose($fp);

print_r($types);
print_r($nums);