Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of array_chunk [duplicate]

Tags:

arrays

php

array_chunk splits an array into multiple arrays using a chunk size to make the cuts.

What if I have an array of arrays of values, and I just want one big array of values?

I could use array_merge, but that would require me to enumerate all the sub-arrays, of which there may be a variable number.

For now, my solution is:

foreach($input as $tmp) {foreach($tmp as $val) {
    ...
}}

But that's kind of messy and only works because I want to use the values. What if I wanted to store the array somewhere?

EDIT: The input is coming from a set of <select multiple> boxes, used to select items from multiple categories. Each item has a globally unique (among items) ID, so I just want to combine the input into a single array and run through it.

The input might look like:

[[4,39,110],[9,54,854,3312,66950],[3]]

Expected output:

[4,39,110,9,54,854,3312,66950,3]

or:

[3,4,9,29,54,110,854,3312,66950]
like image 784
Niet the Dark Absol Avatar asked May 15 '12 12:05

Niet the Dark Absol


People also ask

What is array_ chunk()?

The array_chunk() function splits an array into chunks of new arrays.

Why use array_ chunk in PHP?

The array_chunk() function is used to split an array into arrays with size elements. The last chunk may contain less than size elements. Specifies the array to split. If we set preserve_keys as TRUE, array_chunk function preserves the original array keys.


2 Answers

Code:

$array = [[4,39,110], [9,54,854,3312,66950], [3]];
$array = call_user_func_array('array_merge', $array);

print_r($array);

Result:

Array
(
    [0] => 4
    [1] => 39
    [2] => 110
    [3] => 9
    [4] => 54
    [5] => 854
    [6] => 3312
    [7] => 66950
    [8] => 3
)
like image 105
Viltaly Artemev Avatar answered Nov 02 '22 06:11

Viltaly Artemev


While PHP doesn't have a built in method to flatten an array, you can achieve the same thing using array_reduce and array_merge. Like this:

$newArray = array_reduce($array, function ($carry, $item) {
    return array_merge($carry, $item);
}, []);

This should work as an inverse operation to array_chunk.

like image 44
Darren Avatar answered Nov 02 '22 06:11

Darren