PHP – File to Associative Array with 1 key and two values attached

Try this

// 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); 
} 

Check the $file="orderdata.txt" in your script and add appropriate extension , this will work only if the php file and the orderdata file are in the same path. If not, then provide an absolute path for the file and try

If the input is like this,

[email protected]:1:11    
[email protected]:2:12    
[email protected]:3:13    
[email protected]:4:14

Then the above script will output like

Array
(
    [[email protected]] => Array
        (
            [0] => 1
            [1] => 11    

        )

    [[email protected]] => Array
        (
            [0] => 2
            [1] => 12    

        )

    [[email protected]] => Array
        (
            [0] => 3
            [1] => 13    

        )

    [[email protected]] => Array
        (
            [0] => 4
            [1] => 14
        )

)

Leave a Comment