Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn an array into a map in PHP?

Tags:

php

This is based on a previous question I asked. Lets say I have run an SQL query and received the following into a variable $res:

name    |    language
-------------------------
bob     |   English
bob     |   Dutch
Sally   |   English
Sally   |   Spanish
Sally   |   German

i.e. $res["name"] currently equals the first column etc.

Is there a PHP function or sequence of functions (without writing a loop) to turn $res into a map so that I could write $res["bob"] and receive an array ["English", "Dutch"] or $res["Sally"] and receive ["English", "Spanish", "German"]?

like image 751
twerdster Avatar asked Sep 04 '26 08:09

twerdster


1 Answers

$map = array();
foreach ($mysqlResult as $row) {
    $map[$row['name']][] = $row['language'];
}
like image 153
deceze Avatar answered Sep 05 '26 23:09

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!