'Convert array of single-element arrays to one a dimensional array
I have this kind of an array:
Array
(
[0] => Array
(
[0] => 88868
)
[1] => Array
(
[0] => 88867
)
[2] => Array
(
[0] => 88869
)
[3] => Array
(
[0] => 88870
)
)
I need to convert this to one dimensional array. How can I do that?
For example like this..
Array
(
[0] => 88868
[1] => 88867
[2] => 88869
[3] => 88870
)
Any php built in functionality is available for this array conversion?
Solution 1:[1]
The PHP array_mergeDocs function can flatten your array:
$flat = call_user_func_array('array_merge', $array);
In case the original array has a higher depth than 2 levels, the SPL in PHP has a RecursiveArrayIterator you can use to flatten it:
$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0);
See as well: Turning multidimensional array into one-dimensional array
Solution 2:[2]
try:
$new_array = array();
foreach($big_array as $array)
{
foreach($array as $val)
{
array_push($new_array, $val);
}
}
print_r($new_array);
Solution 3:[3]
$oneDim = array();
foreach($twoDim as $i) {
$oneDim[] = $i[0];
}
Solution 4:[4]
Yup.
$values = array(array(88868), array(88867), array(88869), array(88870));
foreach ($values as &$value) $value = $value[0];
Solution 5:[5]
While some of the answers on the page that was previously used to close this page did have answers that suited this question. There are techniques for this specific question that do not belong on the other page because of the input data structure.
The sample data structure here is an array of single-element, indexed arrays.
var_export(array_column($array, 0));
Is all that this question requires.
Solution 6:[6]
foreach($array as $key => $value){
//check that $value is not empty and an array
if (!empty($value) && is_array($value)) {
foreach ($value as $k => $v) {
//pushing data to new array
$newArray[] = $v;
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Blake Frederick |
| Solution 2 | redmoon7777 |
| Solution 3 | marioosh |
| Solution 4 | benesch |
| Solution 5 | mickmackusa |
| Solution 6 | Somesh Bawane |
