I have an associate array format like $aa. Need to form an array list in the different format.
$aa = Array ( 'Std'=> Array ( 'Add/Remove/Modify', 'Create', 'Addition', 'repository', ), 'Agl' => Array ( 'Disk', 'center', 'Service ', ), 'Error' => Array ( 'VM', 'DNS', 'Upgrade', ), 'Hyg' => Array ( 'Health', 'VM ', 'Clear', ), 'Int' => Array ( 'iExecute', 'Storage', 'CMDB', ), 'Jor' => Array ( 'Uptime ', 'Server ', 'Report', ), 'Mon' => Array ( 'jobs', 'mon', 'SLA', ), );
Have to form the array like the below format in PHP. Help me on this. Thanks in advance
$res = array( array( 'Add/Remove/Modify','Disk', 'VM','Health', 'iExecute','Uptime ', 'jobs' ), array( 'Create','center', 'DNS', 'VM ','Storage','Server ', 'mon' ), array( 'Addition', 'Service ', 'Upgrade', 'Clear', 'CMDB', 'Report','SLA' ), array('repository') );
Advertisement
Answer
array_map() takes an arbitrary number of arrays as arguments(it can do more than the “standard case” with one array), and then step through them one element at a time. A “set”(array) of the current element(s) of each array is passed to a callback function that can “mold” each set of values the way you want them to be (which..is just the way they were passed to the callback, in this case :)).
It’s just the small issue of some of the arrays being longer than others(in that case the size of the set handed to the callback is still the same, but with null values from the shorter arrays). Hence the call to array_filter().
As you perhaps already know by now, telling the story “backwards”, we pass the contents of $aa
– as separate arrays – to array_map(), with the aid of the spread operator(The “outer” one, the spread operator in the function head compacts all the arguments to the array $args
). To unpack the array PHP wants it to be numeric, which $aa
isn’t. Hence array_values().
print_r( array_map( function(...$args) { return array_filter($args); }, ...array_values($aa) ) );