fork download
  1. <?php
  2.  
  3. function custom_array_merge() {
  4. // variable number of inputs
  5. $arrays = func_get_args();
  6.  
  7. // consolidate into array of items => count/array(of counts) across inputs
  8. $counts = array_map('array_count_values', $arrays);
  9. $consolidated = call_user_func_array('array_merge_recursive', $counts);
  10.  
  11. // reduce array of counts (where applicable) to maximum count
  12. $maximums = array_map(function($v) {
  13. return is_array($v) ? max($v) : $v;
  14. }, $consolidated);
  15.  
  16. // build result -- could be faster with array_fill() and concatenating
  17. // but that would definitely use up more memory
  18. $result = [];
  19. foreach ($maximums as $item => $times) {
  20. for ($i = 0; $i < $times; ++$i) {
  21. $result[] = $item;
  22. }
  23. }
  24.  
  25. return $result;
  26. }
  27.  
  28. $result = custom_array_merge(
  29. ['room', 'page', 'room'],
  30. ['book', 'book','book','room'],
  31. ['page', 'room']
  32. );
  33.  
  34. print_r($result);
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
Array
(
    [0] => room
    [1] => room
    [2] => page
    [3] => book
    [4] => book
    [5] => book
)