Question

I am trying to read Data from a text file and then plot it usint PHPplot. Text file looks like this:

0   24
1   28
2   30
3   35
4   40

I am trying to convert the data into something like:

array(array(0,24),array(1,28),array(2,30),array(3,35),array(4,40))

my code in php is like this

 $file = fopen("data2.txt", "r");;
            while (!feof($file)) {
                $line_of_text .= fgets($file);
            }
            $members = explode("\n", $line_of_text);
            fclose($file);

for ($j=0; $j<=10; $j++)
  {       
  $parts[$j]=explode("   ", $members[$j]);       
  }
# plot 
require_once 'phplot.php';
    for ($x = 0; $x <= 5; $x += 1)
      $data[] = array('', $parts[$x][0], $parts[$x][1]);
    $plot = new PHPlot(800, 600);
    $plot->SetPrintImage(False); // No automatic output
    $plot->SetImageBorderType('plain');
    $plot->SetPlotType('lines');
    $plot->SetDataType('data-data');
    $plot->SetDataValues($data);
    $plot->SetPlotAreaWorld(0, 0, 10, 40);
    $plot->SetDrawYGrid(True);
    $plot->DrawGraph();

the problem is in line:

$data[] = array('', $parts[$x][0], $parts[$x][1]);

that it does not draw the $parts[$x][1] numbers. when I say print $parts[$x][1] values it prints it on the browser but just do not plot it. the interesting part is that when I ask it to plot

$data[] = array('', $parts[$x][0], $parts[$x][1]);

It Plots this time!!

var_dump($parts) gave:

array(11) { [0]=> array(2) { [0]=> string(1) "0" [1]=> string(3) "24 " } [1]=> array(2) { [0]=> string(1) "1" [1]=> string(3) "28 " } [2]=> array(2) { [0]=> string(1) "2" [1]=> string(3) "30 " } [3]=> array(2) { [0]=> string(1) "3" [1]=> string(3) "35 " } [4]=> array(2) { [0]=> string(1) "4" [1]=> string(2) "40" } [5]=> array(1) { [0]=> string(0) "" } [6]=> array(1) { [0]=> string(0) "" } [7]=> array(1) { [0]=> string(0) "" } [8]=> array(1) { [0]=> string(0) "" } [9]=> array(1) { [0]=> string(0) "" } [10]=> array(1) { [0]=> string(0) "" } }

also var_dump($data) gave:

array(5) { [0]=> array(3) { [0]=> string(0) "" [1]=> int(0) [2]=> string(3) "24 " } [1]=> array(3) { [0]=> string(0) "" [1]=> int(1) [2]=> string(3) "28 " } [2]=> array(3) { [0]=> string(0) "" [1]=> int(2) [2]=> string(3) "30 " } [3]=> array(3) { [0]=> string(0) "" [1]=> int(3) [2]=> string(3) "35 " } [4]=> array(3) { [0]=> string(0) "" [1]=> int(4) [2]=> string(2) "40" } }

please help me thanks alot

Was it helpful?

Solution

Reza, per your vardump, the values in your array are strings and the array you showed in your question had ints. Here is one way to convert these strings to ints.

    for ($j=0; $j<=10; $j++){
        $tmp=explode("   ", $members[$j]);
        for($k=0; $k<count($tmp); $k++){
            $tmp[$k] = intval($tmp[$k]);
        }
        $parts[$j]=$tmp;     
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top