Appending an Array

Discussion in 'PHP' started by misslilbit02, Feb 16, 2008.

  1. #1
    Hi,

    I want to grab data from a .csv file and add all the data to the array. I have the part where I'm grabbing the data from the .csv file but the array issue I haven't totally figured out.

    Currently, I'm not adding all the data just the last row of data to the array and need help trying to add all the data to the array. Can someone please help me accomplish this. This is what I have:

    
    <?php
    global $info;
    ini_set("auto_detect_line_endings", 1);
    $current_row = 1;
    $handle = fopen("adduser.csv", "r");
    $info="";
    while ( ($data = fgetcsv($handle, 10000, ",") ) !== FALSE )
    {
        $number_of_fields = count($data);
        if ($current_row == 1)
        {
        //Header line
            for ($c=0; $c < $number_of_fields; $c++)
            {
                $header_array[$c] = $data[$c];
            }
        }
        else
        {
        //Data line
            for ($c=0; $c < $number_of_fields; $c++)
            {
                $data_array[$header_array[$c]] = $data[$c];
            }
            print_r($data_array);
    		$info = $data_array;
        }
        $current_row++;
    }
    //buildBatchXML($data_array);
    
    echo "<br><br>This is new data:<br><br>";
    	foreach($info as $key => $value)
    	{
    		echo "$key - $value<br>";
    	}
    	
    fclose($handle);
    
    ?>
    PHP:

     
    misslilbit02, Feb 16, 2008 IP
  2. aaron_nimocks

    aaron_nimocks Im kind of a big deal Staff

    Messages:
    5,563
    Likes Received:
    627
    Best Answers:
    0
    Trophy Points:
    420
    #2
    What do you get if you

    echo $number_of_fields;
    PHP:
     
    aaron_nimocks, Feb 16, 2008 IP
  3. The Critic

    The Critic Peon

    Messages:
    392
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Try doing this:

    
    $info[] = $data_array;
    //snip...
    foreach($info as $data)
    {
    	foreach($data as $key=>$value){echo "$key - $value<br>";}
    }
    
    PHP:
     
    The Critic, Feb 17, 2008 IP
  4. 00johnny

    00johnny Peon

    Messages:
    149
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    critic may have had it but..

    
    for ($c=0; $c < $number_of_fields; $c++)
    {
        $data_array[$header_array[$c]][] = $data[$c];
    }
    
    PHP:
    when you want to append something to an array you use the '[]' operator.
    ie.
    
    $a = array();
    $a[] = 1;
    $a[] = 2;
    $a[] = 3;
    
    // result
    $a = array(1, 2 ,3);
    
    PHP:
     
    00johnny, Feb 17, 2008 IP