Created
June 15, 2017 11:50
-
-
Save devmsh/f22f538ffc5ab9824ae91d4dbbe13aa5 to your computer and use it in GitHub Desktop.
array_assoc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Go from $scores to $result without using any loops! | |
*/ | |
$scores = [ | |
["player_id" => 3, "name" => "player #1", "score" => 150, "bonus" => 200], | |
["player_id" => 4, "name" => "player #2", "score" => 120, "bonus" => 100], | |
]; | |
$result = collect([ | |
3 => ["name" => "player #1", "score" => 350], | |
4 => ["name" => "player #2", "score" => 220], | |
]); | |
function array_assoc($callback, $value) | |
{ | |
return array_reduce(array_map($callback, $value), function($assoc, $row) | |
{ | |
[$key, $value] = $row; | |
$assoc[$key] = $value; | |
return $assoc; | |
}, []); | |
} | |
$result = array_assoc(function ($data) { | |
return [$data["player_id"], [ | |
"name" => $data["name"], | |
"score" => $data["score"] + $data["bonus"], | |
]]; | |
}, $scores); |
EngKhaledB
commented
Jun 15, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment