0

I need to delete a key in an array from a string.

String is translations.fr

Array is

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

Result must be :

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

I think, using exlpode and unset is the good way.

Can you help me ? Thank's

Royce
  • 45
  • 1
  • 1
  • 9

4 Answers4

2

Try this

 unset(ArrayName[key][key].....)
K.B
  • 885
  • 5
  • 10
  • Yes but how build key [key][key] from string ? – Royce Jul 19 '17 at 07:59
  • $keys = explode('.',"translations.fr") ; $keys[0] = translations; $keys[1] = fr; in this you can get keys – K.B Jul 19 '17 at 08:05
  • explode give an array with each key. My problem is to transform this array in $array[$key][$key] – Royce Jul 19 '17 at 08:07
  • try this $keys = explode('.',"translations.fr") ; $keys[0] -> translations; $keys[1] -> fr; ... unset(${$keys[0]}[$keys[1]]); // ${arrayname}[key] – K.B Jul 19 '17 at 08:17
0

Try this :

If you want to replace the same array and delete the "fr" completely

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

If you want to retain the previous array and save the changes in a new one

$translationArrayNew = unset($translationArray['fr']);
Aaditya Damani
  • 355
  • 1
  • 2
  • 12
0

I think this is what you're looking for:

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

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

With explode you put your string into an array containing 2 keys: 0 => translations 1 => fr

This accesses the 'translations' key within your array

$array[$exploded[0]]

and this accesses the 'fr' key within 'translations'

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

it's like writing: $array['translations]['fr']

user1915746
  • 466
  • 4
  • 16
0

Solution :

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];
            }
        }
    }
}
Royce
  • 45
  • 1
  • 1
  • 9