Make PHP Array From Dynamic Number of Columns Queried

109
September 07, 2018, at 6:00 PM

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.

Answer 1

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)
Rent Charter Buses Company
READ ALSO
Finding each record having second largest date for each `key&#39; column in mysql?

Finding each record having second largest date for each `key' column in mysql?

With below code I'm able to get every key with max key_date value

138
MySQL query for highest and lowest sales

MySQL query for highest and lowest sales

I have a table sales as below:

200
Insert with a Select query

Insert with a Select query

I've seen this question asked before, but with the select getting all of the vars for the insert, how can I perform an insert with part strings, part select query?

164