0

I'm newbie in PHP. I wrote the below-given code to create the array "data". It should have 10 rows, BUT for some reason only last (10th) row is filled. The SQL query is fine for sure, because I checked it in MySQL Query Manager (the query returns 10 rows).

$query1="SELECT * FROM tab1, tab2 WHERE tab1.column1=tab2.column2;";
    $result1=DatabaseConnector::ExecuteQueryArray($query1);
    $data = array();
    $i = 0;
    foreach ($result1 as $row):
        $data = array(
            array($i,array("xxx",' EE112',$row['column3'],'FT445'),"2004-03-01 10:00","2004-03-01 14:00"));
        $i++;
    endforeach;

Update 1: I have another related to my initial question. When I try reading data from the array, the error "Undefined offset: 1" occurs. The funny thing is that when I filled "data" array using $data = and not $data[] =, there was no error, just the last row was filled.

for($i=0; $i<count($data); ++$i) {
        $bar = new GanttBar($data[$i][0],$data[$i][1],$data[$i][2],$data[$i][3]);
        $graph->Add($bar);
    }

3 Answers 3

2

That's because you're overriding the entire $data variable on each iteration. Use

$data[] = array(...

As for the newest error - You should be using foreach to iterate an array. That's what it was made for.

4
  • What could mean the error "Undefined offset" while reading this array?? Commented May 17, 2012 at 8:30
  • It means you're trying to access an array key which doesn't exist. Commented May 17, 2012 at 8:34
  • Please look at the update of my thread. I decided to post this error here, because I think it's related to my initial question. If not, I'll open a new thread. Commented May 17, 2012 at 8:56
  • @KlausosKlausos: I have updated my answer. If you have such a complex data structure, don't you think it would be better if you used Objects instead of arrays? Commented May 17, 2012 at 11:39
2

Should like this to append to an array.

$data[] = array($i,array("xxx",' EE112',$row['column3'],'FT445'),"2004-03-01 10:00","2004-03-01 14:00");
1
$data = array(...); // Typecasts $data to a new array with given keys and values
$data[] = array(...); // Typecasts a new array to the next array pointer in $data

Above, line 1 would create a brand new array stored in $data overwriting all previous data. On line 2 the new array would be stored within the already existent array $data.

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.