数组值在函数内部分配但在外部显示为空

时间:2018-01-25 10:55:48

标签: php arrays magento

我在magento网站上工作,当数组值在函数内部分配并在函数外部检索时,我遇到了奇怪的错误。

//define array
$ctall=array();
//function for array value assign
function printtest($fg){
//global variable
    global $ctall;

    //just assign to array
    $ctall[rand(10000,100000)]=$fg; 

 //this var dump shows array with vaues  when function calling
//  var_dump($ctall);
}

我在另一个函数

中调用此函数
$categoryTree = Mage::getResourceModel('catalog/category')->getCategories($categoryId, 0, true);
$printCategories = function($nodes) use (&$printCategories) {

   foreach ($nodes as $_category):
      $ctdf=$_category->getId();
      $categoryn = Mage::getModel('catalog/category')->load($ctdf);
          if($ctdf!='' && $categoryn->getIsActive()):
                //here call to function by passing a value
                printtest($ctdf);   
          $printCategories($_category->getChildren());       
        endif; 
  endforeach; 


};


$printCategories($categoryTree);

//sleep(10);



// i try to get array results here but it shows empty
var_dump($ctall);

任何人都知道如何解决这个问题,我试过几个小时没有运气。谢谢

2 个答案:

答案 0 :(得分:2)

删除$ ctall的所有声明,并尝试:

//remove define array, don't define it
// $ctall=array();

function printtest($fg){

    if(!isset($GLOBALS['ctall'])){
        $GLOBALS['ctall'] = array();
    }
    //assign to global
    $GLOBALS['ctall'][rand(10000,100000)]=$fg;
}

在外面,像这样转储:

var_dump($GLOBALS['ctall'])

答案 1 :(得分:1)

尝试推送而不是分配。试试这个:

$ctall[][rand(10000,100000)]=$fg; //notice the empty square brackets

你也可以试试这个:

function printtest($fg){
  global $ctall;
  $new_array =array();
  $new_array[rand(10000,100000)] = $fg;
  array_merge($ctall, $new_array);
}