note 41181 added to ref.array
| From: | davidj at boundlessgallery dot DISLIKESPAM dot com | Date: | Thu, 01 Apr 2004 22:10:01 +0000 |
| Subject: | note 41181 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-67491@lists.php.net to get a copy of this message | ||
A recursive function for flattening nested arrays:
<?php
function flatten_array($array) {
for($x = 0; $x < sizeof($array); $x++) {
$element = $array[$x];
if(is_array($element)) {
$results = flatten_array($element);
for($y = 0; $y < sizeof($results); $y++) {
$flat_array[] = $results[$y];
}
} else {
$flat_array[] = $element;
}
}
return $flat_array;
}
?>
Example:
<?php
$array = array("0", "1", array("2", "3",
array("4", array("5", "6"), "7", "8")),
"9", "10", array("11"), array());
print_r($array);
print_r(flatten_array($array));
?>
Output:
Array
(
[0] => 0
[1] => 1
[2] => Array
(
[0] => 2
[1] => 3
[2] => Array
(
[0] => 4
[1] => Array
(
[0] => 5
[1] => 6
)
[2] => 7
[3] => 8
)
)
[3] => 9
[4] => 10
[5] => Array
(
[0] => 11
)
[6] => Array
(
)
)
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
)
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41181
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41181&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41181&report=yes
Search -- http://master.php.net/manage/user-notes.php