Enjoy an ad free experience by logging in. Not a member yet?
Register .
09-16-2012, 06:29 PM
PM User |
#1
New to the CF scene
Join Date: Sep 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
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!
09-17-2012, 12:56 AM
PM User |
#2
Senior Coder
Join Date: Jan 2011
Location: Missouri
Posts: 2,395
Thanks: 18
Thanked 351 Times in 350 Posts
<?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 />";
?>
09-17-2012, 03:31 AM
PM User |
#3
Senior Coder
Join Date: Sep 2010
Posts: 1,155
Thanks: 10
Thanked 148 Times in 148 Posts
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.
09-17-2012, 09:16 AM
PM User |
#4
God Emperor
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,662
Thanks: 4
Thanked 2,452 Times in 2,421 Posts
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.
Last edited by Fou-Lu; 09-17-2012 at 09:22 AM ..
Jump To Top of Thread
Thread Tools
Rate This Thread
Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
All times are GMT +1. The time now is 06:11 AM .
Advertisement
Log in to turn off these ads.