gistfile1.txt
· 946 B · Text
Brut
array_map for associative array
https://medium.com/@valerio_27709/php-array-map-for-associative-array-fast-tips-98f98b817a03
ex:
$emails = array_map(function($user) {
return $user['email'];
}, $users);
// Result: ['john.doe@example.com', 'jane.smith@example.com', 'bob.johnson@example.com']
// Using array_map to add the avatar field to each user
$result = array_map(function($user) {
return array_merge(
$user,
[
'avatar' => 'https://eu.ui-avatars.com/api/?background=ff7511&color=fff&name='.$user['first_name']
]
);
}, $users);
Autre exemple:
$histogram = array_map_assoc(function ($key, $value) {
return [
'label' => $key,
'value' => $value['doc_count']
];
}, $data);
### PHP8.4 - Nouveautés
Read about “array_find”, “array_find_key”, “array_any”, and “array_all”
https://ashallendesign-uk.medium.com/new-array-functions-in-php-8-4-dd299bbf020b
| 1 | array_map for associative array |
| 2 | https://medium.com/@valerio_27709/php-array-map-for-associative-array-fast-tips-98f98b817a03 |
| 3 | |
| 4 | ex: |
| 5 | $emails = array_map(function($user) { |
| 6 | return $user['email']; |
| 7 | }, $users); |
| 8 | |
| 9 | // Result: ['john.doe@example.com', 'jane.smith@example.com', 'bob.johnson@example.com'] |
| 10 | |
| 11 | // Using array_map to add the avatar field to each user |
| 12 | |
| 13 | $result = array_map(function($user) { |
| 14 | return array_merge( |
| 15 | $user, |
| 16 | [ |
| 17 | 'avatar' => 'https://eu.ui-avatars.com/api/?background=ff7511&color=fff&name='.$user['first_name'] |
| 18 | ] |
| 19 | ); |
| 20 | }, $users); |
| 21 | |
| 22 | Autre exemple: |
| 23 | $histogram = array_map_assoc(function ($key, $value) { |
| 24 | return [ |
| 25 | 'label' => $key, |
| 26 | 'value' => $value['doc_count'] |
| 27 | ]; |
| 28 | }, $data); |
| 29 | |
| 30 | |
| 31 | ### PHP8.4 - Nouveautés |
| 32 | |
| 33 | Read about “array_find”, “array_find_key”, “array_any”, and “array_all” |
| 34 | |
| 35 | https://ashallendesign-uk.medium.com/new-array-functions-in-php-8-4-dd299bbf020b |
| 36 |