PHP - 文件到关联数组,附加1个键和两个值

时间:2014-06-04 09:14:01

标签: php arrays key associative-array key-value

我有一个包含以下内容的文本文件:

email:number1:number2    
email:number1:number2    
email:number1:number2    
email:number1:number2   

我需要做的是将它们存储在一个关联数组中,其中电子邮件是密钥,数字是值。

我如何用PHP做到这一点?

以下是我到目前为止的尝试

<?php

// file path 
$file = 'orderdata'; 
// open the file and get the resource handle with errors suppressed 
$handle = @fopen($file,'r'); 
// array to hold our values 
$params = array(); 
if($handle) 
{ 
// if handle is there then file was read successfully 
// as long as we aren't at the end of the file 
   while(!feof($handle)) 
   { 
       $line = fgets($handle); 
       $temp = explode(':',$line); 
       $params[$temp[0]] = $temp[1]; 
   } 
   fclose($handle); 
} 

function search_array ( array $array, $term )
{
    foreach ( $array as $key => $value )
        if ( stripos( $value, $term ) !== false )
            return $key;

    return false;
}

?>

1 个答案:

答案 0 :(得分:0)

试试这个

// file path 
$file = 'orderdata.txt';  // REMEMBER TO MENTION THE CORRECT FILE WITH EXTENSION
// open the file and get the resource handle with errors suppressed 
$handle = @fopen($file,'r');  // DONT USE @ while at development since it will suppress errors
// array to hold our values 
$params = array(); 
if($handle) 
{ 
// if handle is there then file was read successfully 
// as long as we aren't at the end of the file 
   while(!feof($handle)) 
   { 
       $line = fgets($handle); 
       $temp = explode(':',$line); 
       $params[$temp[0]][] = $temp[1]; 
       $params[$temp[0]][] = $temp[2]; 
   } 
   fclose($handle); 
} 

检查脚本中的$file = 'orderdata.txt'并添加适当的扩展名,这仅在php文件和orderdata文件位于同一路径时才有效。如果没有,则提供文件的绝对路径并尝试

如果输入是这样的,

test1@example.com:1:11    
test2@example.com:2:12    
test3@example.com:3:13    
test4@example.com:4:14

然后上面的脚本将输出如

Array
(
    [test1@example.com] => Array
        (
            [0] => 1
            [1] => 11    

        )

    [test2@example.com] => Array
        (
            [0] => 2
            [1] => 12    

        )

    [test3@example.com] => Array
        (
            [0] => 3
            [1] => 13    

        )

    [test4@example.com] => Array
        (
            [0] => 4
            [1] => 14
        )

)