user1721449
user1721449

Reputation: 47

Parsing multiple arrays in PHP

I have a CSV file that I am parsing using PHP. However, the output looks as follows:

Array(
    [0] => URL
    [1] => Value
    [2] => Author
)

Array(
    [0] => URL
    [1] => Value
    [2] => Author
)

Array(
    [0] => URL
    [1] => Value
    [2] => Author
)

And so on...

How can I parse each of these individually and/or display only one at random? I've tried using array_values, but that seems to output all arrays, not just one. Any suggestions? Feel free to let me know if there is anything else I can provide. Thanks guys.

Edit: Added some code if it helps - pretty basic.

//CSV to array and parse
function parseCSV() {
    $file = fopen('feeds/data.csv', 'r');
    while (($line = fgetcsv($file)) !== FALSE) {
        //$line is an array of the csv elements
        $arr = $line;

        $url = array_values($arr)[2];
        $author = array_values($arr)[1];

        print_r($arr);
    }

    fclose($file);      
}//end

Upvotes: 0

Views: 400

Answers (2)

Antonio Alexandre
Antonio Alexandre

Reputation: 286

<?php

Class CsvRandomLine
{
    private $line_count=0;
    private $random_element;
    private $handle;
    private $csv_arr;

    function __construct($file='feeds/data.csv')   
    {
        $this->handle = fopen($file, "r");

         $this->sort_one_element();
    }


    //CSV to array and parse
    function randomLine() 
    {
        $i = 0;

        // move pointer to the sorted line
        while($i < $this->random_element)
        {
          $line = fgets($this->handle);
          $i++;
        }        

        $line = fgetcsv($this->handle);


        //add element to $csv_arr with $url and  $author
        $this->csv_arr=array(
                            "url"    =>  $line[2],
                            "author" =>  $line[1]
                        );


    }//end


    function get($property)
    {
        return $this->csv_arr[$property];
    }


    function sort_one_element()
    {
        if($this->line_count!=0)
        {
            $max = $this->line_count;
        }
        else
        {

            $max = $this->countLines();
        }

        $max--;

        $n = rand( 0 , $max );    

        //echo $n;

        $this->random_element = $n;

        rewind($this->handle);        

        $this->randomLine();    


    }


    function countLines()
    {
        $linecount=0;
        while( fgets($this->handle) !== FALSE )
        {
          $linecount++;
        }

        $this->line_count=$linecount;

        return $linecount;            
    }


    function __destruct()
    {
        fclose($this->handle);
    }

}    


// How to use the class:


$csv_r = new CsvRandomLine();
//Construct automatic sort the first element

echo $csv_r->get("author");
echo '<br>';
echo $csv_r->get("url");

echo '<hr>';

//Sorting another element
$csv_r->sort_one_element();

echo $csv_r->get("author");
echo '<br>';
echo $csv_r->get("url");

Upvotes: 1

vikkio
vikkio

Reputation: 91

Well I would load the array with all the records on the csv file (the first $line read is always the header of the csv document, and I would use it to create the result assoc_array keys), then if you want to display one (the first of the result array) or a random (just use array_rand()).

Just a dirty example

$result = [];
$keys = null;
while(($line = fgetcsv($f)) !== false){
    if($keys === null){
        $keys = $line;
        continue;
    }
    $row = [];
    foreach($keys as $position => $key){
        $row[$key] = $line[$position];
    }
    $result[] = $row;
}

// here you will have $result with all the records and you can get the first or do whaterver you want to show just one

In case you need just the bare data and no an assoc_array you could do

$result = [];
$keys = null;
while(($line = fgetcsv($f)) !== false){
    if($keys === null){
        $keys = $line;
        continue;
    }
    $result[] = $line;
}

// here you will have $result (raw data) and $keys (the header of the csv)

Upvotes: 0

Related Questions