Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

arrays - PHP - Remove element from multidimensional String

I have the following string Available:

$flatPath = '0/instances/0';

With this information I want to be able to unset the element from a multidimensional array like this:

$array = [['instances' => [1,2], ['instances' => [3,4]]

Therefor the Result should look like:

$array = [['instances' => [2], ['instances' => [3,4]]

Statically it would look like:

unset($array[0]['instances'][0]);

I want to be able to remove items in any given string path if available in the array. Therefore the solution has to be able to remove any item from a multidimensional array, irrespective of the structure of the $array, as long as the $flatPath exists.

Thank you in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using the code from https://stackoverflow.com/a/9627299/1213708 as a starting point, this code follows the process with a few tweaks.

Exploding using / to split the string into it's parts, then it removes the last key so it can unset() that particular value from the layer above. Then it loops through the keys to find the layer above, and unsets the appropriate value...

$keys = explode('/', $flatPath);
$endKey = array_pop($keys);
$arr = &$array;
foreach ($keys as $key) {
    $arr = &$arr[$key];
}
unset($arr[$endKey]);
unset($arr);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...