使用 func_get_args 编辑数组
我希望使用具有任意数量参数的函数来编辑数组。到目前为止我的代码是:
function setProperty()
{
$numargs = func_num_args();
$arglist = func_get_args();
$toedit = array();
for ($i = 0; $i < $numargs-1; $i++)
{
$toedit[] = $arglist[$i];
}
$array[] = $arglist[$numargs-1];
}
代码的想法是我可以执行以下操作:
setProperty('array', '2nd-depth', '3rd', 'value1');
setProperty('array', 'something', 'x', 'value2');
setProperty('Another value','value3');
产生以下数组:
Array
(
[array] => Array
(
[2nd-depth] => Array
(
[3rd] => value1
)
[something] => Array
(
[x] => value2
)
)
[Another Value] => value3
)
我认为问题在于该行:
$toedit[] = $arglist[$i];
为了实现所需的功能,该行需要什么?
干杯,
I wish to use a function with an arbitrary number of arguments to edit an array. The code I have so far is:
function setProperty()
{
$numargs = func_num_args();
$arglist = func_get_args();
$toedit = array();
for ($i = 0; $i < $numargs-1; $i++)
{
$toedit[] = $arglist[$i];
}
$array[] = $arglist[$numargs-1];
}
The idea of the code being I can do the following:
setProperty('array', '2nd-depth', '3rd', 'value1');
setProperty('array', 'something', 'x', 'value2');
setProperty('Another value','value3');
Resulting in the following array:
Array
(
[array] => Array
(
[2nd-depth] => Array
(
[3rd] => value1
)
[something] => Array
(
[x] => value2
)
)
[Another Value] => value3
)
The issue I believe is with the line:
$toedit[] = $arglist[$i];
What does this line need to be to achieve the required functionality?
Cheers,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先尝试使用 foreach 循环遍历数组。然后,为了处理子项,您可以将其传递给一个子函数,该子函数将获取所有内容。
我还建议首先使用函数 sizeof() 来确定数组有多大,这样您就会知道上限。
Try using foreach to loop through your array first. Then to handle children, you pass it to a child function that will grab everything.
I also recommend using the function sizeof() to determine how big your arrays are first, so you'll know your upper bounds.
在存储新值之前,您需要沿着路径走到目的地。您可以通过参考来做到这一点:
但是这个
$array
应该存储在哪里的问题仍然存在。You need to walk the path to the destination before storing the new value. You can do this with a reference:
But the question where this
$array
should be stored still remains.