Two dimensional array problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Malcolm

    Two dimensional array problem

    I want to put the contents of a csv file into a 2 dimensional array so that
    I can access any element in a $table[x][y] manner and have come up with the
    following code:

    $complete = file("source.cs v");
    $row=0;
    foreach ($complete as $value) {
    $data = explode(",", $value);
    $table[$row] = $data;
    $row++;
    }
    echo "$table[6][4]";

    However the echo statement returns "Array[4]" instead of the 4th element in
    the 6th row.

    Any suggestions on what I ought to be doing please to make $table a proper 2
    dimensional array?

  • Christopher-Robin

    #2
    Re: Two dimensional array problem

    try

    echo $table[6][4];

    without double-quotes.


    if you need to echo more strings with the $table just "add" it with ".",
    like:

    echo "Element ($x,$y): " . $table[$x][$y] . "\n";


    Comment

    • Christopher-Robin

      #3
      Re: Two dimensional array problem

      btw, $table is a proper 2-dim array, but the code could be enhanced

      // first example
      $table = array();
      $file = fopen("source.c sv","r");
      while(!feof($fi le))
      array_push($tab le,fgetcsv($fil e,4096));

      // second example
      $table = array();
      $file = file("source.cs v");
      foreach($file as $id => $item)
      $table[$id] = explode(",",$it em);

      both would result in an array $table, where
      -> the 1st dimension defines the line-number, starting with 0
      -> the 2nd dimension defines the position of the value in that line,
      starting with 0


      Comment

      • Malcolm

        #4
        Re: Two dimensional array problem

        Aha, that's it thanks.


        "Christophe r-Robin" <Christopher-Robin@gmx.de> wrote in message
        news:cj6pob$t0n $05$1@news.t-online.com...[color=blue]
        > try
        >
        > echo $table[6][4];
        >
        > without double-quotes.
        >
        >
        > if you need to echo more strings with the $table just "add" it with ".",
        > like:
        >
        > echo "Element ($x,$y): " . $table[$x][$y] . "\n";
        >
        >[/color]

        Comment

        Working...