1

I have a query which converts item rows of a series of IDs in MySQL table to columns, so the result has variable number of columns (VC). The only items that are not dynamic are the ID, FirstName, LastName. I know the number of variable items (n), which is part of the query.

what I want to do is to have a loop inside PHP while to add these variable columns to the PHP array.

something like this:

$someArray = [];

while($row = $result -> fetch_assoc()) {

array_push($someArray,[ 

  'ID' => $row['EmployeeID'],
  'FName' => $row['FName'],
  'MName' => $row['MName'],
  'LName' => $row['LName'],

-------Loop here --------
  'VC1' => $row['VC1'],
  'VC2' => $row['VC2'],
  'VC3' => $row['VC3'],
  'VC4' => $row['VC4'],
  'VC5' => $row['VC5'],
  ..............
  'VCn' => $row['VCn']
-------------------------

]);
}

I tried with PHP loop and could not figure out how to do it. Thanks for any help in advance.

1
  • Show us the query, this sounds a little odd so it would help us understand the question Commented Sep 6, 2018 at 18:20

1 Answer 1

2

If you know n you can use for loop:

for($i = 1;$i <= $n; $i++) {
    $key = "VC" .$i;
    $someArray[$key] = $row[$key];
}

However, if you pushing the entire array in it may be better do modify your SQL query and do just:

while($row = $result -> fetch_assoc())
    array_push($someArray, $row)
Sign up to request clarification or add additional context in comments.

2 Comments

Undefined constant n, make it $n
Thanks, it works after I saw your edited answer. thanks a lot.

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.