I have a n dimensional array, and I want to retrieve array value using other variable,
Example: Suppose $a is a 5 dimensional array. I want to get values of $a[3][4], where '3_4' is coming as a parameter string. If parameter be 1_2_3 then that means I want to retrieve or change value of $a[1][2][3]. If parameter be 1_2_3_1 then that means I want to retrieve or change value of $a[1][2][3][1].
Please help me how to achieve this using PHP.
Thanks with Regards,
Ranjit Paul,
Limtex, Kolkata
Retrieve value from a n-dimensional array by dynamic index
Moderator: General Moderators
Re: Retrieve value from a n-dimensional array by dynamic index
Code: Select all
$array = array(/* ... */);
$parameters = explode("_", "1_2_3_4");
$a = $array;
foreach ($parameters as $offset) {
if (!isset($a[$offset])) break; // bad parameter
$a = $a[$offset];
}Re: Retrieve value from a n-dimensional array by dynamic index
hi tasairis,
thanks for your reply
to change the value of the index position
Code would be something like:
thanks for your reply
to change the value of the index position
Code would be something like:
Code: Select all
$array = array(/* ... */);
$parameters = explode("_", "1_2_3_4");
$a =& $array;
foreach ($parameters as $offset) {
if (!isset($a[$offset])) break; // bad parameter
$a = &$a[$offset];
}
$a = $value_to_set;