note 76940 added to ref.array
| From: | pedja at uzice dot net | Date: | Tue, 07 Aug 2007 00:38:25 +0000 |
| Subject: | note 76940 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-129240@lists.php.net to get a copy of this message | ||
Here is the function that cleans array of empty records. It goes recursive through multidimensional
array and erases any item that has empty value or is empty array.
This actually works on any variable type, not just arrays.
<?php
function clean_item ($p_value) {
if (is_array ($p_value)) {
if ( count ($p_value) == 0) {
$p_value = null;
} else {
foreach ($p_value as $m_key => $m_value) {
$p_value[$m_key] = clean_item ($m_value);
if (empty ($p_value[$m_key])) unset ($p_value[$m_key]);
}
}
} else {
if (empty ($p_value)) {
$p_value = null;
}
}
return $p_value;
}
?>
Example:
<?php
$m_array['aaa'] = 'bbb';
$m_array['ccc'] = '';
$m_array['ddd'] = Array();
$m_array['eee']['fff'] = Array();
$m_array['eee']['ggg'] = '';
$m_array['eee']['hhh'] = 'iii';
$m_array['eee']['j']['a'] = 'gh';
$m_array['eee']['j']['b'] = '';
$m_array['eee']['j']['c'] = 'rty';
$m_array['eee']['j']['d'] = Array();
$m_array['eee']['j']['e'][1] = 'r';
$m_array['eee']['j']['e'][2] = 'y';
$m_array['eee']['j']['e'][1] = '';
$m_array['eee']['j']['e'][4] = Array();
$m_array['eee']['j']['e'][5] = '';
$m_clean = $seo->clean_item ($m_array);
print_r ($m_array);
print_r ($m_clean);
?>
Variable $m_clean contains:
Array
(
[aaa] => bbb
[eee] => Array
(
[hhh] => iii
[j] => Array
(
[a] => gh
[c] => rty
[e] => Array
(
[2] => y
)
)
)
)
?>
----
Server IP: 69.147.83.197
Probable Submitter: 77.46.252.25
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit -- https://master.php.net/note/edit/76940
Del: integrated -- https://master.php.net/note/delete/76940/integrated
Del: useless -- https://master.php.net/note/delete/76940/useless
Del: bad code -- https://master.php.net/note/delete/76940/bad+code
Del: spam -- https://master.php.net/note/delete/76940/spam
Del: non-english -- https://master.php.net/note/delete/76940/non-english
Del: in docs -- https://master.php.net/note/delete/76940/in+docs
Del: other reasons-- https://master.php.net/note/delete/76940
Reject -- https://master.php.net/note/reject/76940
Search -- https://master.php.net/manage/user-notes.php