CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   PHP (http://www.codingforums.com/forumdisplay.php?f=6)
-   -   Explode .txt file into multidimensional array. (http://www.codingforums.com/showthread.php?t=273285)

Gokhan137 09-16-2012 06:29 PM

Explode .txt file into multidimensional array.
 
Currently I have a file that looks something like this:

Code:

Awesomedude123 = 399,408 = September 16, 2012:
Username11 = 1,914,144 = September 16, 2012:
EpicSurfer = 1,031,427 = September 16, 2012:

What I want to do is transform it into a multidimensional array with PHP so it looks something like this:

Code:

Array
(
    [1] => Array
        (
            [0] => Awesomedude123
            [1] => 399,408
            [2] => September 16, 2012
        )

    [2] => Array
        (
            [0] => Username11
            [1] => 1,914,144
            [2] => September 16, 2012
        )

    [3] => Array
        (
            [0] => EpicSurfer
            [1] => 1,031,427
            [2] => September 16, 2012
        )

)

I have tried several PHP scripts, but none of them worked for me. Any help would be HIGHLY appreciated!

sunfighter 09-17-2012 12:56 AM

<?php
$MyArray = array
(
1 => array ("Awesomedude123","399,408","September 16, 2012"),
2 => array("Username11", "1,914,144", "September 16, 2012"),
3 => array("EpicSurfer", "1,031,427", "September 16, 2012"),
);

echo $MyArray[2][0]."<br />";
echo $MyArray[2][1]."<br />";
echo $MyArray[2][2]."<br />";
?>

DrDOS 09-17-2012 03:31 AM

If you're on Linux, or otherwise have access to the bash shell you can use the 'while read' loop functionality. PHP may have something similar. It reads a text file line by line and returns it to the caller. the caller can be another loop of any kind. You can separate the lines with the ' = ' and remove the trailing : to get each item.

Fou-Lu 09-17-2012 09:16 AM

There are a few ways to do this.
PHP Code:

$file = array(
    
'Awesomedude123 = 399,408 = September 16, 2012:',
    
'Username11 = 1,914,144 = September 16, 2012:',
    
'EpicSurfer = 1,031,427 = September 16, 2012:',
);

$a = array();
foreach (
$file AS $item)
{
    
$a[] = sscanf(rtrim($item':'), '%s = %s = %s');
}

print_r($a); 

Replace the $file with that of a call to file().

Edit:
I like dos' suggestion too. Reading line by line is actually better than pulling a full string or an array.
Look into the use of fscanf instead, which saves the need for a file() and foreach() call.


All times are GMT +1. The time now is 01:13 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.