0

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
12
  • 1
    array[0] ? or something like that ? Commented Dec 1, 2016 at 10:19
  • What O/P you expected ? Commented Dec 1, 2016 at 10:20
  • 3
    is not really clear what is the problem you should show us your parsing code as well Commented Dec 1, 2016 at 10:20
  • Added a bit of code it it helps. My problem is I am trying to display only one array's values at a time - even better if I can find out how to display a random one each time. Commented Dec 1, 2016 at 10:23
  • Can we assume that one of these arrays is produced from a single line from your csv file? Question is Unclear, more imformation/code would be useful if you want any actual help Commented Dec 1, 2016 at 10:23

2 Answers 2

1
<?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");
Sign up to request clarification or add additional context in comments.

4 Comments

This seems to work great, but only when I remove the fact that it is inside a function.
You're right, I forgot to call the function in the code above. Now added: parseCSV();
Example of csv(feed/data.csv): 1,Alexandre,www.samurai.com 2,Captain Comando,www.capitaincomando.com 3,Puffgirl,www.powerpuffgirls.com 4,Opa Gangnam Style,www.opagangnamstyle.com
Change $this->csv_arr=array( "url" => $line[2], "author" => $line[1] ); to modify or add cloumns of the csv.
0

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)

4 Comments

Of course you could just do $all_lines[] = $line; in the loop and save writing all that code.
@RiggsFolly the problem with that is that you will not have an assoc, you will have $all_lines[0] to be the header of the csv, and everything else to be a not assoc_array with the data payload.
This gives me a more readable format, but seems to be a multidimensional array now
@user1721449 I thought that was what you wanted, if you just want the raw output line by line you could do soemthing using RiggsFolly suggestion. I will update the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.