如何在数组中找到用点分隔的键 - php

时间:2015-09-01 09:40:22

标签: php arrays

我有这个键“this.key.exists”。密钥可以是:a.b.c.d.e.f等,这只是一个例子。

我想检查是否存在于数组中:

$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
            ],
       ]
  ]
];

我需要找到此密钥以更新其值

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

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

$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";