inserting file data into double array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Amzul
    New Member
    • Oct 2007
    • 130

    inserting file data into double array

    hello all,


    i have a roblam that need some new view.

    i have a file that contain ip | country

    what i am tring to do is to know how many ips i have from each country.

    the file looks like that :

    34.34.34.34 | US
    34.24.24.24 | US
    12.12.12.12 | UK
    10.10.10.10 | FR

    my out put should say that i have
    3 countrys (US,UK,FR)
    and in US 2 ips: ip,ip.
    in UK 1 ip: ip.
    in FR 1 ip: ip.

    i mange to create array with string index for all the countrys
    but from here i am stock.

    please help

    here is a bit of code i done so far
    [CODE=php]<?php
    $countrys = array();
    $file = "ip_list.tx t";
    $handle = @fopen($file,"r ");
    if ($handle) {
    while(!feof($ha ndle)){
    $line = explode("|",fge ts($handle, 4096));
    $countrys[$line[1]]=array();
    }
    echo count($countrys );
    print_r($countr ys);
    ?>[/CODE]
    what i need to do now the way i see it is to
    go over the file agian and
    Code:
    if $line[1] == string_index          //US==US 
    then country["US"][0]= 34.34.34.34
    how can it be done?
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    No, you only read the file once. Then you build an array with the country as key and the sub-array holding the ip addresses.
    When done reading, you just walk the array using 'foreach' and print out the contents of the array. Like this[php]<?php
    $countrys = array();
    $file = "test.txt";
    $handle = fopen($file,"r" );
    if ($handle) {
    while(!feof($ha ndle)){
    $line = explode("|",fge ts($handle, 4096));
    $countrys[trim($line[1])][]=$line[0];
    }
    echo count($countrys );
    echo '<pre>';print_r ($countrys);
    foreach($countr ys as $key => $arr) {
    echo "<br>$key : ";
    foreach ($arr as $ipad)
    echo "$ipad ";
    }
    }
    ?>[/php]The output of your sample file will then be:
    Code:
    4
    US : 34.34.34.34  34.24.24.24  
    UK : 12.12.12.12  
    FR : 10.10.10.10
    When you nhave any questions about this code, holler!
    Ronald
    Last edited by ronverdonk; Feb 29 '08, 04:13 PM. Reason: typo

    Comment

    Working...