I have an array in a PHP class and two member functions
First one receives two integers, one is the dimension and the other is the value:
private $complexArray;
function setValueToGivenDimension($dimension, $value)
What I want to do is to set the value to the given dimension of the array.
For example, If I call the function as the following:
setValueToGivenDimension(3,"key","myValue")
I want the array to be
array [
0 => array [
0 => array [
"key" => "myValue"
]
]
]
And Second is function getValueOfGivenDimension($dimension, $key)
For example, If I call the function as the following:
getValueOfGivenDimension(3,"key")
It should return value of the given key which is 0 in this case of the 3rd dimension of the $complexArray:
"myValue"
*array can have any level of dimension and I want to create and index dimensions of the array dynamically.
1 Answer
You can use recursion for both.
The following method will return the array you desire, so you can set your private variable to the output.
function setValueToGivenDimension($dimension, $value) {
// Base case: if the dimension is 0, then we should return the value
if ($dimension == 0) return $value;
// If the dimension is greater than 0, then return the recursive function call, wrapped in a new array
return [setValueToGivenDimension($dimension - 1, $value)];
}
The following method will take an array, dimension, and key, and output the value for the nth dimension of that array, using the key in the innermost dimension.
function getValueOfGivenDimension($array, $dimension, $key) {
// Base case: if the function is at dimension 1, then return the value at the given key for the array
if ($dimension == 1) return $array[$key];
// If the dimension is greater than 0, then recursively call the function on the only child of the given array
return getValueOfGivenDimension($array[0], $dimension - 1, $key);
}
2
setValueToGivenDimension every time returns a new array, but I want to update the existing array only, and what if I want to set a value with a key?
–You could use my definition as a helper function. Your actual function could simply set your array to the value of my function.