The database has the following lines:

 A, A1, A2, A3
 A, A4, A5, A6
 A, A7, A8, A9
 ...
 B, B1, B2, B3
 B, B4, B5, B6
 B, B7, B8, B9
 ...

I need to get an output array:

[A => [[A1, A2, A3], [A4, A5, A6], ...], B => [[B1, B2, B3], [B4, B5, B6], ...] ]

Please tell me how to do it correctly.

  • Rephrase the question. Database cannot have fields. - Anatol
  • one
    Literally select * from table , then assembled with the function PDO :: fetchall, how here ru.stackoverflow.com/questions/504422/… - Mike
  • @Mike, thanks for the reply. If it doesn't bother you, could you write the code, I can't figure it out yet. Revised the documentation, did not find anything unfortunately. I decided to just repeat the code suggested by your link, without specifying the second parameter, it works, but the grouping is not the same, by index, with the second parameter - it gives out emptiness. - tonchikp
  • one
    And what could not get there, now I tried on a table like yours. select col1, col2 from table and fetchall from that answer produced exactly the array you need. can you select extra columns in select - Mike
  • one
    I chose exactly as in the example, without the second parameter. And I choose the columns by clearly specifying two, which of them are needed, the one by which it is necessary to group - the first. Otherwise, the fetch will of course understand nothing if there are more columns or not in that order (why the second parameter does not work - xs). - Mike

1 answer 1

We will use the function that chooses the PDO::fetchAll array at PDO::fetchAll and the PDO::fetchAll selection FETCH_GROUP that will group the data by the first column and FETCH_NUM will make the row arrays indexed only by the column order (excluding the column names).

 $sql = "select X,col1,col2 from TableX"; $stmt = $db->query($sql); $result = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_NUM); 
  • Thank you for the answers. Everything worked out! That's what it means to take up the business with a fresh head, I'm sorry that I did not immediately guess. - tonchikp