我正在处理一个多维数组,其中包含可变数量的空对象。我已经编写了一个脚本来简单地unset()空的,它工作得很好。然而,即使没有echo()函数,当我的循环运行时,也会打印非空值,我似乎不明白为什么。
使用run through my loop的数组示例:
Array
(
[0] => Group Object
(
[_title] => <strong>Abdomen</strong><ul>
[_issues] => <li><strong>Ascites</strong>: 1</li><li><strong>Blood Clot</strong>: 2</li>
)
[1] => Group Object
(
[_title] => <strong>Air Sac</strong><ul>
[_issues] => <li><strong>Cloudy</strong>: 1</li>
)
[2] => Group Object
(
[_title] => <strong>Beak Treatment</strong><ul>
[_issues] => <li><strong>Severe</strong>: 3</li>
)
[3] => Group Object
(
[_title] =>
[_issues] =>
)
[4] => Group Object
(
[_title] =>
[_issues] =>
)
[5] => Group Object
(
[_title] => <strong>Crop</strong><ul>
[_issues] => <li><strong>Impacted</strong>: 2</li>
)
[6] => Group Object
(
[_title] => <strong>Feathering</strong><ul>
[_issues] => <li><strong>Soiled</strong>: 1</li>
)
[7] => Group Object
(
[_title] => <strong>Feet</strong><ul>
[_issues] => <li><strong>Swollen</strong>: 1</li>
)
[8] => Group Object
(
[_title] =>
[_issues] =>
)
[9] => Group Object
(
[_title] =>
[_issues] =>
)
[10] => Group Object
(
[_title] => <strong>Heart</strong><ul>
[_issues] => <li><strong>Compromised</strong>: 1</li>
)
[11] => Group Object
(
[_title] => <strong>Hock</strong><ul>
[_issues] => <li><strong>Clear Exudate</strong>: 2</li>
)
[12] => Group Object
(
[_title] =>
[_issues] =>
)
[13] => Group Object
(
[_title] =>
[_issues] =>
)
[14] => Group Object
(
[_title] =>
[_issues] =>
)
[15] => Group Object
(
[_title] => <strong>Kidney</strong><ul>
[_issues] => <li><strong>Injured</strong>: 2</li>
)
)
foreach()循环清除数组内的空对象:
foreach ($issues as $key => $link) {
if ($issues[$key] != '') {
unset($issues[$key]);
}
}
最后,循环运行时打印的输出:
<strong>Abdomen</strong><ul>
<li><strong>Ascites</strong>: 1</li>
<li><strong>Blood Clot</strong>: 2</li>
<strong>Air Sac</strong><ul>
<li><strong>Cloudy</strong>: 1</li>
<strong>Beak Treatment</strong><ul>
<li><strong>Severe</strong>: 3</li>
<strong>Crop</strong><ul>
<li><strong>Impacted</strong>: 2</li>
<strong>Feathering</strong><ul>
<li><strong>Soiled</strong>: 1</li>
<strong>Feet</strong><ul>
<li><strong>Swollen</strong>: 1</li>
<strong>Heart</strong><ul>
<li><strong>Compromised</strong>: 1</li>
<strong>Hock</strong><ul>
<li><strong>Clear Exudate</strong>: 2</li>
<strong>Kidney</strong><ul>
<li><strong>Injured</strong>: 2</li>
显然,我只想删除空组,不打印任何内容。
正如这里所建议的,您可以使用array_filter
class Foo {
public $bar;
public function __construct($arg)
{
$this->bar = $arg;
}
public function isEmpty()
{
if (is_string($this->bar) && !empty($this->bar))
{
return false;
}
return true;
}
}
$array = array(
new Foo(29),
new Foo(''),
new Foo('hello'),
new Foo(null),
new Foo('world'),
);
function obj_is_empty($obj)
{
return ( ! $obj->isEmpty() );
}
print "<pre>";
var_dump(array_filter($array, "obj_is_empty"));
没问题
我可能错了,但是你的数组应该有引号包围的项目:
[_title] => "<strong>Abdomen</strong><ul>"
您正在检查数组keys
(_title, _issues),而不是values
(腹腔等)