开发者

How to turn an array into a map in PHP?

开发者 https://www.devze.com 2023-02-20 12:15 出处:网络
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:

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开发者_如何学JAVA 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"]?


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


You can do it with mysql using group by :

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


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 :)


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;
}, []);
0

精彩评论

暂无评论...
验证码 换一张
取 消