开发者

loop with two columns in a text file

this is a sample text file called da开发者_JAVA技巧ta.txt

john engineer
mathew IT consultant
elan Vice president
emili administrator
joicee nurse

$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    foreach ($lines as $names => $designation) { 

    //I am not sure above one is right?? then what??
    }

I want this to be loaded in two variables

$names = john;
$designation = Engineer;

and loop through...


The lines in $lines aren't a 'name' => 'designation' map by default; you have to manually break the lines apart.

You can use explode for this. You'll have to add 2 as the optional "limit" parameter, to insure the lines are broken up at only the first space:

$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($lines as $line) {
  list($name, $designation) = explode(' ', $line, 2);
}

Without the limit, lines like "elan Vice president" would be broken up as array("elan", "Vice", "president") instead of array("elan", "Vice president").


If your format is always using space as delimiter between $name, an $designation, this might work

foreach ($lines as $line_number => $line) 
{
  $space = strpos($s, ' ');
  $name  = substr($s, 0, $space);
  $designation = substr($s, $space+1);
}


If "names" and "designations" are separate with tabulation, you can use something like this :

foreach ($lines as $line) { 
  list($name, $designation) = explode("\t", $line);
  ...
}


Tty following code. Its work::

$lines = file('new.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
list($name[], $job[]) = explode(' ', $line,2);
}
foreach($name as $n=>$value)
 echo "Name= ".$name[$n]." Job=".$job[$n]."<br>";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜