我正在使用以下代码丢失数组中的数据:
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
数组。我希望函数的第一行在第一次调用函数时只执行一次。
我有什么方法可以做到吗?
答案 0 :(得分:2)
您可以使用不同方式对此进行归档。我将在这里展示一些:
静态变量
使您的数组保持静态,因此初始化仅在第一次函数调用时完成,例如
function addIndexKey($parent) { static $myKeys = array(); //Will only be initialized once //... }
可选参数
使您的参数可选,并且不会在第一个函数调用上传递数组,例如
function addIndexKey($parent, $myKeys = []) { //Now call the function like this: addIndexKey($parent, $myKeys) } addIndexKey($parent)//First call without the optional argument, which means it gets initialized
(类属性)
由于您对函数具有可见性,因此我假设您在一个类中,这意味着您可以使用$myKeys
作为类属性,您可以使用空数组进行初始化,例如
class XY { protected $myKeys = []; private function addIndexKey($parent) { //Use '$this->myKeys' here } }
答案 1 :(得分:1)
是
$count = 0;
private function addIndexKey($parent) {
global $count;
if(count == 0)
$myKeys = array();
$count++
...
}
答案 2 :(得分:0)
当你的函数第一次运行时,你可以将变量设置为false,并在函数内部检查是否为真,然后运行你的第一行。
$isFirstTime = true;
function Your_function_name(){
global $isFirstTime;
if ($isFirstTime){
//Run some code
}
$isFirstTime = false;
}
答案 3 :(得分:0)
检查$ myKeys是否已经创建,或者它是否是一个数组,具体取决于您之前在代码中执行的操作,位于函数的第一行。
if( !is_array($myKeys) )$myKeys = array();
//OR EITHER
if( !isset($myKeys) )$myKeys = array();