将多维数组存储为对象变量,并向数组添加附加键

发布于 2024-10-08 05:06:06 字数 1134 浏览 2 评论 0原文

所以我有一个存储在对象中的多维数组。我想向这个数组添加额外的键。

这是我所拥有的:

$object->pathsArray = array(
    "key1" => array('path' => '/some/path/to/some/file.php', 'action' => 'index'),
    "key2" => array('path' => '/some/path/to/some/class.php', 'action' => 'method2')
);

这是我认为可行但没有的:

$object->pathsArray['key3'] = array('path' => '/some/path/to/some/method/or/script.php', 'action' => 'method3');

我的第一个解决方法:

$newPathsArray = array("key3" => array('path' => '/some/path/to/some/method/or/script.php', 'action' => 'method3'));   
$object->pathsArray = array_merge($object->pathsArray, $newPathsArray);

另一个应该有效的解决方法:

$tempPathsArray = $object->pathsArray;
$tempPathsArray['key3'] = array('path' => '/some/path/to/some/method/or/script.php', 'action' => 'method3');
$object->pathsArray = $tempPathsArray;

所以我的问题:是否有更简单的语法(即:一行解决方案)或者我是否被迫引入临时变量。变量,附加到该变量然后合并/重新分配值给对象?

So I have a multidimensional array which is stored in an object. I want to add additional keys to this array.

Here's what I have:

$object->pathsArray = array(
    "key1" => array('path' => '/some/path/to/some/file.php', 'action' => 'index'),
    "key2" => array('path' => '/some/path/to/some/class.php', 'action' => 'method2')
);

And here's what I assumed would work but did not:

$object->pathsArray['key3'] = array('path' => '/some/path/to/some/method/or/script.php', 'action' => 'method3');

My first workaround:

$newPathsArray = array("key3" => array('path' => '/some/path/to/some/method/or/script.php', 'action' => 'method3'));   
$object->pathsArray = array_merge($object->pathsArray, $newPathsArray);

Another workaround that SHOULD work:

$tempPathsArray = $object->pathsArray;
$tempPathsArray['key3'] = array('path' => '/some/path/to/some/method/or/script.php', 'action' => 'method3');
$object->pathsArray = $tempPathsArray;

So my question: Is there a simpler syntax (ie: one line solution) or am I forced to bring in a temp. variable, append to that then merge/re-assign the value to the object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抚笙 2024-10-15 05:06:06

很抱歉写下答案,但我无法发表评论。
我认为仅仅为了使用一个属性而公开它是不正确的。正确的做法应该是创建一个 setter 来填充它,而不是仅仅为此修改类设计。

Sorry to write an answer, but I'm not able to comment.
I think that it's not correct to make an attribute public just to use it by that way. The correct thing should be make a setter to fill it, not modifying the class design just for that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文