我正在使用一个多维数组,其中包含可变数量的空对象。我写了一个脚本来简单地取消设置()空的脚本,它工作正常。但是,即使没有echo()函数,我的循环运行时也会打印非空值,而我似乎无法弄清楚原因。
将使用遍历我的循环的数组示例:
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>
显然,我只想删除空组,不打印任何内容。任何帮助表示赞赏。
答案 0 :(得分:1)
根据建议here,您可以使用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"));
工作正常
答案 1 :(得分:0)
我可能错了,但你的数组应该包含引号括起来的项目:
[_title] => "<strong>Abdomen</strong><ul>"
否则无论发生什么都是不可预测的。
答案 2 :(得分:0)
您正在检查数组keys
(_title,_issues),而不是values
(Abdomem等)。