开发者

PHP arrays - simple way to change value of relative location in deep associative array

I have a script that is handling an array in $_SESSION, however I want to change one specific value within that array. I could go the nested foreach route, however I think I am missing a simpler solution.

The branch of the array that I want to change looks like

$_SESSION['roles'][$group][$role]['status'] = 'disabled';

This is of course easy to change if I know the $group and $role variables开发者_如何转开发, however for the script I am trying to write I simply want to change the first instance of ['status'] to 'active'. (That is the status of the first $role in the first $group of the $_SESSION['roles'] array

I tried

$_SESSION['roles'][key($_SESSION['roles'])][key(current($_SESSION['roles']))]['status'] = 'active';

which works, but this also seems clumsy. Am I missing a simple function here?


There's no better solution. "Relative/sequential access" and "associative arrays" don't fit together very well anyway.

Btw, depending on what you did with the array before you'll have to reset() it sokey()` returns the first key.

Edit: For the first part you could replace $_SESSION['roles'][key($_SESSION['roles'])] with reset($_SESSION['roles']). That returns the first element of the array. If PHP allows you to pass a non-variable to reset() you can do the same for the inner array, i.e. reset(reset($_SESSION['roles'])).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜