Using func_get_args to edit an array
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');
开发者_JS百科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,
You need to walk the path to the destination before storing the new value. You can do this with a reference:
function setProperty() {
$numargs = func_num_args();
if ($numargs < 2) return false; // not enough arguments
$arglist = func_get_args();
// reference for array walk
$ar = &$array;
// walk the array to the destination
for ($i=0; $i<$numargs-1; $i++) {
$key = $arglist[$i];
// create array if not already existing
if (!isset($ar[$key])) $ar[$key] = array();
// update array reference
$ar = &$ar[$key];
}
// add value
$ar = $arglist[$numargs-1];
}
But the question where this $array
should be stored still remains.
class foo {
private $storage;
function setProperty()
{
$arglist = func_get_args();
if(count($argslist) < 2) return false;
$target = &$this->storage;
while($current = array_shift($arglist)){
if(count($arglist)==1){
$target[$current] = array_shift($arglist);
break;
}
if(!isset($target[$current])) $target[$current] = array();
$target = &$target[$current];
}
}
}
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.
精彩评论