简体   繁体   中英

php access to specific position of multidimensional array by its keys and set it

In PHP we can do things like these:

Class Example {
 ...
}
$example = 'Example';
$object = new $example();

Or the use of variable variables:

$hour = 18;
$greets = array('Good morning','Good afternoon','Good evening');
$values = array(13,21,23);//people is sleeping at 23PM, so they don't greet.
$n = count($values);
$greet = 'greets';
for($i=0;$i<$n;$i++){
   if($hour < $values[$i]){
       echo 'hello, '.${$greet}[$i];
       break;
   }
}

And others..

I wonder if it would be possible to access directly to a specific index of a multidimensional array in a similar way. Something like:

$array = array(...); //multidimensional array.
$position = '[0][4][3]';
print_r($array$position);

Thanks in advance.


UPDATE

I'm so sorry because I finished my question in a wrong way.

I need to set the multimesional array and add a value. ie:

$array$position = $data;

You could implement it yourself with a custom function:

function getValueFromMultiDimensionalArray( array $array, string $key )
{
    $keys = explode('][', $key);
    $value = $array;

    foreach ($keys as $theKey) {
        // remove the opening or closing bracket if present
        $theKey = str_replace([ '[', ']' ], '', $theKey);

        if (!isset($value[$theKey])) {
            return null;
        }

        $value = $value[$theKey];
    }

    return $value;
}

You can define path as dot separated , check the following solution

function getValueByKey($a,$p){
  $c = $a; 
  foreach(explode('.',$p) as $v){
    if(!array_key_exists($v, $c)) return null;
    $c =  $c[$v];
  }
  return $c;
}

You can use this function as

$path = '1.2.3.0';
$indexValue = getValueByKey($array, $path);

Nope, this is not possible. The only thing you can do is to implement ArrayAccess interface, which allows to access instances with [] operator. But you will have to define the logic yourself.

class MyClass implements ArrayAccess
{
...
}

$x = new MyClass([0=>[4=>[3=>'hello world']]]);
$position = '[0][4][3]';
echo $x[$position]; //hello world

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM