无法将对象减少到所需信息

时间:2017-04-30 19:00:38

标签: php arrays object

我有一个包含一个对象的配置,其中包含有关我系统的所有相关信息。其中一部分列出了系统中当前的所有等级:

return (object) array(
    //User Ranks
    "Ranks" => (object) array(
        "Developer" => (object) array(
            //Admin, User, Banned, Deactivated, Pending Moderation, Pending Email Activation
            "AccountState" => "Admin",
            //Page View Permission
            "PagePermissions" => array(
                "cadet/dashboard",
                "admin/dashboard",
                "admin/users"
            ),
            "TaskPermissions" => array(
                "BasicUserSearch",
                "AdvancedUserSearch",
                "GetRanks",
                "EditUser"
            )
        ),
        "Staff" => (object) array(
            "AccountState" => "Admin",
            //Page View Permission
            "PagePermissions" => array(
                "cadet/dashboard",
                "admin/dashboard",
                "admin/users"
            ),
            "TaskPermissions" => array(
                "BasicUserSearch",
                "AdvancedUserSearch"
            )
        )
    )
);

我需要做的是将此对象转换为一个简单的数组以返回到AJAX调用。该数组必须如下所示:

(
   "Developer" => array("AccountState" => "Admin), 
   "Staff" => array("AccountState" => "Admin)
)

我尝试使用此代码执行此操作:

public function GetRanks(){
    $LstRanks = (array)$this->config->Ranks;

    for($i = 0; $i < count($LstRanks); $i++){
        $LstRanks[$i] = array_column($LstRanks[$i], "AccountState");
    }
    return json_encode(["data" => 0, "ranks" => $LstRanks]);
}

但是,函数的第一行返回null,导致循环不断循环并产生错误。如图所示切割对象的最佳方法是什么?

错误

[30-Apr-2017 18:38:47 UTC] PHP Notice:  Undefined offset: 0 in /home/thomassm/public_html/php/lib/UserSystem.php on line 23
[30-Apr-2017 18:38:47 UTC] PHP Warning:  array_column() expects parameter 1 to be array, null given in /home/thomassm/public_html/php/lib/UserSystem.php on line 23

1 个答案:

答案 0 :(得分:0)

public function GetRanks(){
    $Ranks = (array) $this->config->Ranks;
    $LstRanks = array();

    foreach($Ranks as $StrRank => $LstRankInfo){
        $LstRanks[$StrRank] = $LstRankInfo->AccountState;
    }

    return json_encode(["data" => 0, "ranks" => $LstRanks]);
}

这是我使用评论建议的解决方案。似乎我错误地将对象变成了一个数组。