twerdster
twerdster

Reputation: 5027

How to turn an array into a map in 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"]?

Upvotes: 6

Views: 12632

Answers (4)

Cyrusmith
Cyrusmith

Reputation: 757

Another option is to use array_reduce:

$rows = array_from_sql_query();

$map = array_reduce($rows, function($res, $row) {
  $res[$row['name']][] = $row['language'];
  return $res;
}, []);

Upvotes: 0

alex
alex

Reputation: 490303

If there were a native function, it would use a loop internally anyway.

$res = array();
foreach($old as $value) {
   $res[$value['name']][] = $value['language'];
}

Edit: I see this is a one to many relationship :)

Upvotes: 1

Spyros
Spyros

Reputation: 48636

You can do it with mysql using group by :

http://www.tizag.com/mysqlTutorial/mysqlgroupby.php

Upvotes: 1

deceze
deceze

Reputation: 522165

$map = array();
foreach ($mysqlResult as $row) {
    $map[$row['name']][] = $row['language'];
}

Upvotes: 11

Related Questions