我在我的数组中难倒,在函数中添加了值之后没有保存。我认为变量不在函数范围内是一个问题。我有以下变量:
$oldInterestIdArray = array();
$newInterestsIdArray = array();
我有一些函数来填充数组:
function oldInterestIds($value, $key)
{
$data = fetchInterestDetail($value);
$id = $data['id'];
$oldInterestIdArray[] = $id;
}
function getNewInterestIds($value,$key)
{
if(interestExists($value))
{
$data = fetchInterestDetail($value);
$id = $data['id'];
$newInterestsIdArray[] = $id;
}
else
{
addInterest($value);
$data = fetchInterestDetail($value);
$id = $data['id'];
$newInterestsIdArray[] = $id;
}
}
if(count($errors) == 0)
{
$newInterests = array_diff($interestsArray, $interests);
$common = array_intersect($interestsArray, $interests);
$toChangeId = array_diff($interests, $common);
array_walk($toChangeId, "oldInterestIds");
array_walk($newInterests, "getNewInterestIds");
echo json_encode($oldInterestIdArray);
}
}
但$ oldInterestIdArray返回空白。但是,如果我在oldInterestIds
函数内部回显json,它会让我相信这是变量范围的问题。我尝试将变量更改为:
global $oldInterestIdArray;
global $newInterestsIdArray;
但是返回null。有什么建议吗?
答案 0 :(得分:1)
在函数内声明global $oldInterestIdArray;
,如
function oldInterestIds($value, $key)
{
global $oldInterestIdArray; // set here global;
$data = fetchInterestDetail($value);
$id = $data['id'];
$oldInterestIdArray[] = $id;
}
参见 Example
答案 1 :(得分:0)
将您的数组作为参考传递:
function oldInterestIds(&$arr, $value, $key)
{
$data = fetchInterestDetail($value);
$id = $data['id'];
$arr[] = $id;
}