Jump to content

Extracting data from csv to a 2d array


elyfrank

Recommended Posts

Hi guys,

This is my problem:

I have a csv file let's say have these values:

 

blue,1,2,3,4

red,8,5,6,7

 

I need to add thes values into a 2d array

to be able to use like this:

colors[1][2]=2

colors[2][4]=7

 

Where my first number is the row and the second number is the value within that row.

 

This is what I got so far

 

<?PHP

$i=0;

$j=0;

$file_handle = fopen("color-list.csv", "r");

while (!feof($file_handle) )

{

$colors = fgetcsv($file_handle, 10000);

 

for ($j=0; $j<=4; $j++)

{

$row[$i][$j]=$colors[$j];

                                        print row[$i][$j];

}

$i++;

?>

 

For some reason this doesn't work. Maybe I am declaring the arrays wrong. :confused:

 

Thank you!

Link to comment
https://forums.phpfreaks.com/topic/212516-extracting-data-from-csv-to-a-2d-array/
Share on other sites

Hey sasa,

How do I compare and sort this array?

I am adding a new value at the end of the arrays like this

$colors[$i][repeat]=$x;

After I added the value I would like to compare and sort the array base on that value

I have something like this so far and it is not working:

function compare($x, $y)

{

if ( $colors[repeat] == $colors[repeat] )

  return 0;

else if ( $colors[repeat] < $colors[repeat] )

return -1;

else

  return 1;

}

 

uasort($colors, 'compare');

print_r($colors);

 

function compare($x, $y)
      {
       if ( $x['repeat'] == $y['repeat'] )
        return 0;
       else if ( $x['repeat'] < $y['repeat'] )
       return -1;
       else
        return 1;
      }

uasort($colors, 'compare');
print_r($colors);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.