doubaomao9304 2014-08-11 05:05
浏览 101
已采纳

Php:数组返回空

I am stumped on my array is not being saved after having values added to it in the functions. I believe it is a problem with the variables not being in the scope of the function. I have the following variables:

$oldInterestIdArray = array();
$newInterestsIdArray = array();

and I have some functions to populate the arrays:

    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);
        }

    }

But the $oldInterestIdArray is returning blank. But if I were to echo json inside the oldInterestIds function it works, which leaves me to believe this is a problem with the variables scope. I have tried changing the variable to:

global $oldInterestIdArray;
global $newInterestsIdArray;

But that is returning null. Any suggestions?

  • 写回答

2条回答 默认 最新

  • dongrenzheng1619 2014-08-11 05:11
    关注

    declare global $oldInterestIdArray; inside the function like

      function oldInterestIds($value, $key)
        {
            global $oldInterestIdArray; // set here global;
            $data = fetchInterestDetail($value);
            $id = $data['id'];
            $oldInterestIdArray[] = $id;
        }
    

    See Example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写