0

Looking for some help if possible.

$pilotsids is an array of ids. merged is the table that holds the data. For each pilotid, I'd like to create an array of newrat values, which I am going to use later to populate a chart. The index of the for loop must be added to the name of each array like this:

$data0[]
$data1[]
$data2[]...etc

It works when I do it separately:

$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[0] order by mid asc"); 
    while($row = mysqli_fetch_assoc($result)) {
       $data0[] = $row['newrat'];
    } 
$result = $mysqli->query("select newrat from merged where pilotid = '$pilotids[1]' order by mid asc"); 
    while($row = mysqli_fetch_assoc($result)) {
       $data1[] = $row['newrat'];
    } 
$result = $mysqli->query("select newrat from merged where pilotid = '$pilotids[2]' order by mid asc"); 
    while($row = mysqli_fetch_assoc($result)) {
       $data2[] = $row['newrat'];
    } 

It doesn't if I try to to iterate automatically for lets say 10 times:

for($i=0; $i < 10; $i++) {
        $result = $mysqli->query("select newrat from merged where pilotid = $pilotids[$i] order by mid asc"); 
        while($row = mysqli_fetch_assoc($result)) {
            ${$data.$i}[] = $row['newrat'];  
            
        }
   }
1
  • 1
    Using variable names like $data0 usually would be better handled by an array - in your case a two dimensional array. Something like $data[0][] when adding the new data. Commented May 7, 2022 at 12:26

1 Answer 1

1

You can try this way:

$data = [];
for($i=0; $i < 10; $i++) {
    $result = $mysqli->query("select newrat from merged where pilotid = $pilotids[$i] order by mid asc"); 
    while($row = mysqli_fetch_assoc($result)) {
        $data[$i][] = $row['newrat'];
    }
}

As you can see I'm using a two dimensional array which is defined outside of the loop.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Would the above output the index in the name of the array like $data0, $data1, $data2...etc ? I need it for the chart to recognize which dataset to parse. I tried it anyway, no errors but the chart did not pick it up.
The output will be one aray containing multiple arrays.
Thanks so much. Only your last comment made me realize better use a 2 dimensional array. I was trying to literally print out the index in the name of the array.
Yeah you were trying to use separate variables with the index in it. It is easier however in a multidimensional array especially if you have dynamic amount (or large amount) of entries.

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.