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
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);

 

Link to comment
Share on other sites

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);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.