How can I do the below change in PHP?
Input:
[hiddenAllPrefered] => Array
(
[0] => 14477,14478,14479,14485,14486,14487
)
Output should be like this:
[hiddenAllPrefered] => Array
(
[0] => 14477,14478,14479
[1] => 14485,14486,14487
)
How can I do the below change in PHP?
Input:
[hiddenAllPrefered] => Array
(
[0] => 14477,14478,14479,14485,14486,14487
)
Output should be like this:
[hiddenAllPrefered] => Array
(
[0] => 14477,14478,14479
[1] => 14485,14486,14487
)
A possible solution:
$input = array('14477,14478,14479,14485,14486,14487');
$output = array_map(
function (array $a){
return implode(',', $a);
},
array_chunk(
explode(',', $input[0]),
3
)
);
Read it from inside out:
explode() splits the string $input[0] using comma (,) as delimiter and returns an array;array_chunk() splits the array into chunks of size 3; it returns an array of arrays, each inner array contains 3 elements (apart from the last one that can contain less);array_map() applies the function it receives as its first argument to each value of the array it gets as its second argument (the array of arrays returned by array_chunk()); it returns an array whose values are the values returned by the function;array_map() gets an array (of size 3 or less) and uses implode() to join its elements into a string, using comma (,) to separate the values and returns the string;array_map() puts together all the values returned by the anonymous function (one for each chunk of 3 elements of the array) into a new array it returns.The output (print_r($output)) looks like this:
Array
(
[0] => 14477,14478,14479
[1] => 14485,14486,14487
)