Note Submitter: pedja at uzice dot net
----
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
)
)
)
)
?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.