PHP: Turning multidimensional arrays to single dimension arrays

http://stackoverflow.com/questions/2408892/php-turning-multidimensional-arrays-to-single-dimension-arrays

//combine array to 1 big array after query the database

$bigarray = array();
while ( $row = mysql_fetch_array($resultsN) ) {
array_push($bigarray, $row);
}

//the result become single array.
$result = array();
$result = flatten_array($bigarray);

reset($result);
while (list($key, $val) = each($result)) {
echo “$key => $val\n”;
}

//this function merge multi-dimensional array to 1 array.
function flatten_array($mArray) {
$sArray = array();

foreach ($mArray as $row) {
if ( !(is_array($row)) ) {
if($sArray[] = $row){
}
} else {
$sArray = array_merge($sArray,flatten_array($row));
}
}
return $sArray;
}//

 

Advertisements
This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s