array_map usage


/ Published in: PHP
Save to your folder(s)

shows how to use array_map to mine data from nested arrays.


Copy this code and paste it in your HTML
  1. <?php
  2. // from this nested array I want to extract only the user_id's
  3. $arr = array(
  4. array('User' => array('user_id' => 100, 'device_id' => 2100, 'name' => 'a', 'role' => 'admin')),
  5. array('User' => array('user_id' => 101, 'device_id' => 2101, 'name' => 'b', 'role' => 'admin')),
  6. array('User' => array('user_id' => 102, 'device_id' => 2102, 'name' => 'c', 'role' => 'admin')),
  7. array('User' => array('user_id' => 103, 'device_id' => 2103, 'name' => 'd', 'role' => 'admin')),
  8. array('User' => array('user_id' => 104, 'device_id' => 2104, 'name' => 'e', 'role' => 'admin')),
  9. array('User' => array('user_id' => 105, 'device_id' => 2105, 'name' => 'f', 'role' => 'admin')),
  10. );
  11.  
  12. // this is how to do it using anonymous function
  13. $new = array_map(function($n){return $n['User']['user_id'];}, $arr);
  14.  
  15. // Use a global function
  16. function map_func($n){
  17. return $n['User']['user_id'];
  18. }
  19. $new2 = array_map('map_func', $arr);
  20.  
  21. // Call a static function in a class
  22. class MyMapper{
  23. static function map_func($n){
  24. return $n['User']['user_id'];
  25. }
  26. }
  27.  
  28. $callable = array('MyMapper', 'map_func');
  29. $new3 = array_map($callable, $arr);
  30.  
  31. // Using a function from an object.
  32. $myMapperObject = new MyMapper;
  33. $callable = array($myMapperObject, 'map_func');
  34. $new4 = array_map($callable, $arr);
  35.  
  36. echo "=========================\n";
  37. print_r($new);
  38. print_r($new2);
  39. print_r($new3);
  40. print_r($new4);
  41. echo "=========================\n";

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.