Using a string path to remove an item from an array

I have an array like this

$arr = [ 'baz' => [ 'foo' => [ 'boo' => 'whatever' ] ] ]; 

Anyway, to turn off the value of '' boo '] using line input?

Something like that

  $str = 'baz->foo->boo'; function array_unset($str, $arr) { // magic here unset($arr['baz']['foo']['boo']); return $arr; } 

This answer was awesome, and it made the first part of my script run using the string path to set the data of nested arrays , but it cannot undo. Postscript eval () is not an option: (

+6
source share
3 answers

Since you cannot invoke unset on the reference element, you need to use a different trick:

 function array_unset($str, &$arr) { $nodes = split("->", $str); $prevEl = NULL; $el = &$arr; foreach ($nodes as &$node) { $prevEl = &$el; $el = &$el[$node]; } if ($prevEl !== NULL) unset($prevEl[$node]); return $arr; } $str = "baz->foo->boo"; array_unset($str, $arr); 

Essentially, you go through the array tree, but keep a reference to the last array (the penultimate node) from which you want to remove the node. Then you call unset in the last array, passing the last node as the key.

Check this code

+9
source

This one is similar to Huysentruit's Wouter. The difference is that it returns null if you pass an invalid path.

 function array_unset(&$array, $path) { $pieces = explode('.', $path); $i = 0; while($i < count($pieces)-1) { $piece = $pieces[$i]; if (!is_array($array) || !array_key_exists($piece, $array)) { return null; } $array = &$array[$piece]; $i++; } $piece = end($pieces); unset($array[$piece]); return $array; } 
+1
source

Something on the fly that might work for you:

 $str = 'bar,foo,boo'; function array_unset($str,&$arr) { $path = explode(',',$str); $buf = $arr; for($i=0;$i<count($path)-1;$i++) { $buf = &$buf[$path[$i]]; } unset($buf); } 
0
source

Source: https://habr.com/ru/post/945615/


All Articles