如何在数组中找到由点分隔的键 - php [duplicate]

问题描述:

This question already has an answer here:

I have this key "this.key.exists". Key can be: a.b.c.d.e.f etc. this is only example.

And i want to check if exists in array:

$array = [ // depth of array and number of values are variable
  'this' => [
       'key' => [
           'exists' => 'some value' // this is what am i looking for
       ],
       'key2' => [
           'exists' => 'some value' // this is not what am i looking for
       ],
  ],
  'that' => [
       'this' => [
            'key' => [
                'exists' => 'some value' // this is not what am i looking for
            ],
       ]
  ]
];

I need to find this key for update his value.

$array['this']['key']['exists'] = 'need to set new value'; 

Thanks for help

</div>

$str = "this.key.exists";

$p = &$array;                               // point to array root
$exists =  true;
foreach(explode('.', $str) as $step) { 
   if (isset($p[$step])) $p = &$p[$step];   // if exists go to next level
   else { $exists = false; break; }         // no such key  
}

if($exists) $p = "new value";