note 57270 deleted from ref.array by aidan
| From: | aidan@php.net | Date: | Sun, 09 Oct 2005 09:10:38 +0000 |
| Subject: | note 57270 deleted from ref.array by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-96720@lists.php.net to get a copy of this message | ||
Note Submitter: Ryan M (popthestack)
----
Basically, I needed to flatten an array by removing everything from a multi-dimensional array except
the last array in each array (did that even make sense?). I tried several of the functions in these
notes, but none worked the way I needed them to.
Here is my array_flatten function in a class:
<?php
class Whatever {
var $flat_array;
function array_flatten(&$array) {
foreach($array as $sub) {
if(is_array($sub)) {
$this->array_flatten($sub);
}
else {
$this->flat_array[$array['id']] = $array;
}
}
return $this->flat_array;
}
};
?>
NOTE: I add the item to the new array using $array['id'] If you use just [] you get lots
of duplicates.
usage (omitting the creation of the multi-dimensional associative array):
<?php
$myclass = new Whatever();
$flat_array = $myclass->array_flatten($myarray);
?>
Sample array before flattening:
Array
(
[9] => Array
(
[9] => Array
(
[id] => 9
[parent_category_id] => 5
[name] => Test Category
[short_description] => this is a test category
[long_description] => testing 123
[sort_order] => 1
[visible] => 1
)
[10] => Array
(
[10] => Array
(
[id] => 10
[parent_category_id] => 9
[name] => a test sub category
[short_description] => more testing
[long_description] =>
[sort_order] => 1
[visible] => 1
)
[11] => Array
(
[11] => Array
(
[id] => 11
[parent_category_id] => 10
[name] => a sub-sub category
[short_description] => yes, even more testing
[long_description] =>
[sort_order] => 1
[visible] => 1
)
)
)
)
)
The above example will output:
Array
(
[9] => Array
(
[id] => 9
[parent_category_id] => 5
[name] => Test Category
[short_description] => this is a test category
[long_description] => testing 123
[sort_order] => 1
[visible] => 1
)
[10] => Array
(
[id] => 10
[parent_category_id] => 9
[name] => a test sub category
[short_description] => more testing
[long_description] =>
[sort_order] => 1
[visible] => 1
)
[11] => Array
(
[id] => 11
[parent_category_id] => 10
[name] => a sub-sub category
[short_description] => yes, even more testing
[long_description] =>
[sort_order] => 1
[visible] => 1
)
)