8 Replies - 1030 Views - Last Post: 17 July 2011 - 12:54 PM Rate Topic: -----

#1 theone2k1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 17-July 11

How to format the data in text file into my desirable array format?

Posted 17 July 2011 - 12:11 AM

Peter
http//yahoo.com
Joe
http//google.com
http://ebay.com
Dave
http//foo.com
http//facebook.com
http//stackoverflow.com
Vincent
http//example.com
http//php.net
Terry
http//apple.com

data.txt goes on with hundreds of names and links in similar format.

ok... I have a text data file. I want to use PHP to put the name as one element and combine the link(s) between the names into one element rather than each link a separate element in an array. I tried to do it but got stuck. :( Hope you guys help me out.

here's what i have so far.

<?php

$data = file_get_contents('data.txt');
$data_exploded = explode ("\n",$data);

$arraysize = count($data_exploded);

$z=0;

$newarray = array();
$namearr = array();
$linksarr = array();
$finalarr = array();
$numlink =array();  //array that stores number of links btwn names
echo "array size $arraysize <br />";
var_dump($data_exploded);
//index interval between the file names 
for($i=0; $i<$arraysize; $i++){
//check if it is a name
if(substr($data_exploded[$i], 0, 4)!=="http"){
$name =$i;
array_push($newarray,$name); //the index number of names store in this array
}
}
$i_i=0;
$newarray_size = count($newarray);

//calculate the number of links btwn the name intervals
for($i_i=0; $i_i< $newarray_size-1; $i_i++){

$link = $newarray[$i_i+1]-$newarray[$i_i]-1;
array_push($numlink,$link); //store the number of links in this array
}
echo $maxnumlink = max($numlink); //the high number of links in the array
//loop through the main array
for($j=0; $j<$arraysize; $j++){
if(in_array($j, $newarray)){  //check to see if it is a name
array_push($finalarr,$data_exploded[$j]);
}else{
$z = $j + $maxnumlink;
for($k=$j; $k<=$z; $k++){
if(substr($data_exploded[$k], 0, 4)!=="http"){
break;
}
array_push($finalarr,$data_exploded[$k]);
}
}
}
?>


Is This A Good Question/Topic? 0
  • +

Replies To: How to format the data in text file into my desirable array format?

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 2889
  • View blog
  • Posts: 7,535
  • Joined: 08-June 10

Re: How to format the data in text file into my desirable array format?

Posted 17 July 2011 - 03:31 AM

you could write an ini file and read that by parse_ini_file(). with some minor modification to the text file your PHP code becomes
$data = parse_ini_file("data.txt");

Was This Post Helpful? 0
  • +
  • -

#3 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: How to format the data in text file into my desirable array format?

Posted 17 July 2011 - 06:32 AM

Hi,

What do you want your end array to look like? Do you want it to be a name in one element then the next hold all the links for that user? Or did you want to have separate name and link arrays?

Also you should really start using code indentation this will make your code easier for everyone, including yourself, to read.
Was This Post Helpful? 1
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5667
  • View blog
  • Posts: 22,511
  • Joined: 23-August 08

Re: How to format the data in text file into my desirable array format?

Posted 17 July 2011 - 07:46 AM

Assuming you're attempting what Jstall said, and you don't want to/can't modify the data file appropriately as Dormilich suggested, here's a handout with comments to help you understand:

<?php

// Pass the array and currentName by reference as we're                         
// modifying them within the function.                                          
function processLine(&$list, &$currentName, $line)
{
    // Is this line a name?                                                     
    // If it doesn't start with http, we will assume so.                        
    if (strncmp($line, 'http', 4) != 0) {
        // Assign contents of $line to the $currentName variable                
        $currentName = $line;

        // Add the $currentName to our array as the key                         
        // and create the array to hold the links                               
        $list[$currentName] = array();
    } else {
        // This is a link.                                                      
        // Use the $currentName as the key and assign the                       
        // $line to the array for the $currentName, if it exists,               
        // else skip it.                                                        
        if ($currentName == null) {
            echo ("No \$currentName variable set; skipping\n");
        } else {
            $list[$currentName][] = $line;
        }
    }
}

// The final array                                                              
$list = array();

// file() reads each line into an array element, so                             
// you can use foreach on it                                                    
foreach (file('names.txt') as $line) {

    // The $line variable contains the newline character,                       
    // so strip it off                                                          
    $line = trim($line);

    // Call our function to handle the $line                                    
    processLine($list, $currentName, $line);
}

// Print our list                                                               
print_r($list);

?>



Output:
php -f names.php 
Array
(
    [Peter] => Array
        (
            [0] => http://yahoo.com
        )

    [Joe] => Array
        (
            [0] => http://google.com
            [1] => http://ebay.com
        )

    [Dave] => Array
        (
            [0] => http://foo.com
            [1] => http://facebook.com
            [2] => http://stackoverflow.com
        )

    [Vincent] => Array
        (
            [0] => http://example.com
            [1] => http://php.net
        )

    [Terry] => Array
        (
            [0] => http://apple.com
        )

)


Was This Post Helpful? 1
  • +
  • -

#5 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2485
  • View blog
  • Posts: 8,523
  • Joined: 08-August 08

Re: How to format the data in text file into my desirable array format?

Posted 17 July 2011 - 08:38 AM

You could use filter_var:
<?php
$data = file("data.txt");
$final = array();
foreach($data as $val) {
	$val = str_replace("\n","",$val);
	if(!filter_var($val, FILTER_VALIDATE_URL)) {
		$key = $val;
		$final[$val] = array();
	} else {
		$final[$key][] = $val;
	}
}
print_r($final);
?>


Edit: Note that I did a find/replace to change all http// to http:// in your data to make the addresses valid URLs.

This post has been edited by CTphpnwb: 17 July 2011 - 09:09 AM

Was This Post Helpful? 2
  • +
  • -

#6 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5667
  • View blog
  • Posts: 22,511
  • Joined: 23-August 08

Re: How to format the data in text file into my desirable array format?

Posted 17 July 2011 - 09:08 AM

Nice use of filter_var!
Was This Post Helpful? 0
  • +
  • -

#7 theone2k1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 17-July 11

Re: How to format the data in text file into my desirable array format?

Posted 17 July 2011 - 10:08 AM

You guys are the best! I spent the past week thinking how to do it.(You can tell i am a beginner.) This is what I need! Thank you so much! :bananaman:

This post has been edited by theone2k1: 17 July 2011 - 10:13 AM

Was This Post Helpful? 0
  • +
  • -

#8 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 934
  • View blog
  • Posts: 2,329
  • Joined: 15-February 11

Re: How to format the data in text file into my desirable array format?

Posted 17 July 2011 - 10:35 AM

Just adding in my two cents...

You may have already found your solution but for future reference you could use the functions serialize and unserialize.

It's useful if you won't be editing the file manually since it would be a bit tricky.

Example
<?php
$a = array('codeprada' => 
array('http://www.website.com', 'http://www.another.com'),
			  'member' => 
array('http://www.member.com', 'http://www.anothermember.com'));
print_r($b = serialize($a));
echo "<br /><br />";
print_r(unserialize($B)/>);
?>

This post has been edited by codeprada: 17 July 2011 - 10:36 AM

Was This Post Helpful? 0
  • +
  • -

#9 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2485
  • View blog
  • Posts: 8,523
  • Joined: 08-August 08

Re: How to format the data in text file into my desirable array format?

Posted 17 July 2011 - 12:54 PM

View Posttheone2k1, on 17 July 2011 - 01:08 PM, said:

I spent the past week thinking how to do it.

We could tell by your code that you had put some effort into it, which is why we don't mind showing you a quick solution: we know you'll learn from it. ;)

One thing I want to point out is an important difference between your code and ours: indentation. When code is indented properly it is easier to read because the indents have meaning. The easier code is to read, the easier it is to debug.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1