Tags
PHP , array
Asked 7 years ago
21 Dec 2016
Views 2887
jessica

jessica posted

how to convert multidimensional array to single dimensional array in php

how to convert multidimensional array to flat array . flat array means single dimensional array ,

$records = array(
    array(
        'id' => 2135,
        'first_name' => 'jessica',
        'last_name' => 'ram',
    ),
     'id'=>2134,
    array(
        'id' => 5342,
        'first_name' => 'Ram',
        'last_name' => 'ranghuvanshi',
    ) 
);

 
 
$first_names = array_column($records, 'first_name');
print_r($first_names);


it give firstname list only but i need to make array with single dimensional with all value . do not want to skip any value from array.

shyam

shyam
answered Nov 30 '-1 00:00

you are using proper function . array_column will work for making of multidimensional array to single dimensional

if you dont want to skip any value or need all value of array need to convert in single dimensional than i have some code what i used for my application

$array=array(
	"data",
 array("is","money")
 );
 $flat_array;
 function flat_array($array){
	global $flat_array;
	foreach($array as $value){
		if(is_array($value)){
		 flat_array($value); 
		}else {
			$flat_array[]=$value;
			 
		}
		
	}
	 
 }
 flat_array($array);
 print_r($flat_array);
any short code than this ? either it is ok - jessica  
Dec 21 '16 00:07
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00


$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($records)  
);
var_dump( $iterator); PHP_EOL;
foreach ($iterator as $key => $leaf) {
    echo " $leaf", PHP_EOL;
}


LET ME EXPLAIN HOW RecursiveIteratorIterator work with Multidimensional array

RecursiveIteratorIterator take first argument as Traversable iterator , so we covert array to Recursive ArrayIterator by RecursiveArrayIterator class.

new RecursiveArrayIterator($records)

RecursiveIteratorIterator is working with differ mode . its optional . default mode is RecursiveIteratorIterator::LEAVES_ONLY , which means give all leaves values.

we used RecursiveIteratorIterator::LEAVES_ONLY mode so it will result all value in flat array from multidimensional array.
Post Answer