2017-07-19 126 views
0

我需要从字符串中删除数组中的某个键。如何从字符串中删除数组元素

字符串是translations.fr

阵列是

[ 
    ..., 
    translations => [ 
      fr => [ 
       ... 
      ], 
      es => [ 
       ... 
      ] 
    ], 
    ..., 
] 

结果必然是:

[ 
    ..., 
    translations => [ 
      es => [ 
       ... 
      ] 
    ], 
    ..., 
] 

我认为,使用exlpodeunset是很好的方式。

你能帮我吗?感谢的

+2

使用PHP未设置()方法为 –

+0

'未设置($ translation_arr [ 'FR']);'会工作。 –

+0

试试这个,https://stackoverflow.com/questions/369602/delete-an-element-from-an-array – dadan

回答

0

解决方案:

public function deleteKeyV3($keyToDelete) { 
    $keys = explode('.', $keyToDelete); 
    $result = &$array; 

    foreach ($keys as $key) { 
     if (isset($result[$key])) { 
      if ($key == end($keys)) { 
       unset($result[$key]); 
      } else { 
       $result = &$result[$key]; 
      } 
     } 
    } 
} 
2

试试这个

unset(ArrayName[key][key].....) 
+0

是的,但是如何从字符串构建key [key] [key]? –

+0

$ keys = explode('。',“translations.fr”); $ keys [0] =翻译; $ keys [1] = fr;在这里你可以得到钥匙 – kranthi

+0

爆炸给每个关键的数组。我的问题是将这个数组转换为$ array [$ key] [$ key] –

0

试试这个:

如果你想更换同一阵列并删除“FR”完全

$translationArray = unset($translationArray['fr']); 

如果要保留以前的数组并将其保存在新的变化中

$translationArrayNew = unset($translationArray['fr']); 
0

我认为这是你在找什么:

$str = 'translations.fr'; 
$exploded = explode('.', $str); 
$array = [ 
     'translations' => [ 
       'fr' => 'fr value', 
       'es' => 'es value', 
       ] 
     ]; 

unset($array[$exploded[0]][$exploded[1]]); 

随着explode你把你的串入含2个键的数组: 0 =>翻译 1 => FR

该项访问“翻译”您的阵列内的关键

$array[$exploded[0]] 

这个访问中的“FR”钥匙“翻译”

$array[$exploded[0]][$exploded[1]] 

它就像写:$array['translations]['fr']