将多维数组存储为对象变量,并向数组添加附加键
所以我有一个存储在对象中的多维数组。我想向这个数组添加额外的键。
这是我所拥有的:
$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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很抱歉写下答案,但我无法发表评论。
我认为仅仅为了使用一个属性而公开它是不正确的。正确的做法应该是创建一个 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.