【发布时间】:2015-11-27 20:13:21
【问题描述】:
我正在使用以下代码从数组中丢失数据:
private function addIndexKey($parent) {
$myKeys = array();
foreach ($parent->children as $child) {
$pos = $child->varGet('flow_pos');
if (!isset($pos))
$pos = $child->position;
if (isset($child->index))
$myKeys["$pos"] = $child->index;
if (isset($child->children) && count($child->children)>0) {
$subkeys = $this->addIndexKey($child);
if (count($subkeys)>0)
$myKeys["$pos"] = $subkeys;
}
}
ksort($myKeys);
return $myKeys;
}
我正在遍历一个数组,当我返回 $myKeys 数组时,有时会丢失数据。
我假设它是因为在第三个条件下再次调用相同的函数时重新定义了 $myKeys 数组。我希望函数的第一行在第一次调用函数时只执行一次。
有什么办法可以做到吗?
【问题讨论】:
-
我一直在努力解决这个问题,但还没有成功。如果我将其设为静态,我会得到值,但是当它循环大量时间时,我会得到非常大的数组,其中大部分是空的。有什么办法可以删除所有空索引并只保留那些有值的索引?
-
使用
array_filter()去掉空值,例如$myKeys = array_filter($myKeys);