PHP实现多维数组指定路径元素的读取、修改与删除功能
Hey folks, let's solve this problem of accessing, modifying, and deleting specific members in your multidimensional $myContactsBook array using a path parameter. I'll walk you through each operation with clear, reusable code.
First, let's restate your target array for reference:
$myContactsBook = [ 'relatives' => ['bob', 'john'], 'friends' => [ 'work' => ['andrew', 'eric'], 'mars' => ['zoopzap'] ] ];
We'll use path parameters that can be either a dot-separated string (like 'friends.work.1') or an array of keys/indexes (like ['friends', 'work', 1]) — both will work with our functions.
1. Read Operation (Get a Nested Value)
This function will traverse the array using the provided path and return the value if it exists, or null if the path is invalid.
function getNestedValue(array $array, string|array $path): mixed { // Convert dot-separated string to array if needed if (is_string($path)) { $path = explode('.', $path); } $current = $array; foreach ($path as $key) { if (!isset($current[$key])) { return null; // Path doesn't exist } $current = $current[$key]; } return $current; } // Example usage: echo getNestedValue($myContactsBook, 'relatives.1'); // Outputs: john echo getNestedValue($myContactsBook, ['friends', 'mars', 0]); // Outputs: zoopzap echo getNestedValue($myContactsBook, 'friends.school'); // Outputs: null
2. Edit Operation (Update a Nested Value)
This function modifies the original array (note the & pass-by-reference) at the specified path. If the path doesn't exist, it will automatically create nested arrays to match the path (you can adjust this to throw an error instead if needed).
function setNestedValue(array &$array, string|array $path, mixed $value): void { if (is_string($path)) { $path = explode('.', $path); } $current = &$array; foreach ($path as $key) { // Create nested array if key doesn't exist if (!isset($current[$key]) || !is_array($current[$key])) { $current[$key] = []; } $current = &$current[$key]; } $current = $value; } // Example usage: setNestedValue($myContactsBook, 'friends.work.0', 'andy'); print_r($myContactsBook['friends']['work']); // Outputs: Array ( [0] => andy [1] => eric ) // Create a new nested entry setNestedValue($myContactsBook, 'friends.hobby.0', 'lisa'); print_r($myContactsBook['friends']['hobby']); // Outputs: Array ( [0] => lisa )
3. Remove Operation (Unset a Nested Value)
This function deletes the value at the specified path from the original array. It will do nothing if the path doesn't exist.
function unsetNestedValue(array &$array, string|array $path): void { if (is_string($path)) { $path = explode('.', $path); } $current = &$array; $lastKey = array_pop($path); // Traverse to the parent of the target key foreach ($path as $key) { if (!isset($current[$key]) || !is_array($current[$key])) { return; // Path doesn't exist, exit early } $current = &$current[$key]; } if (isset($current[$lastKey])) { unset($current[$lastKey]); } } // Example usage: unsetNestedValue($myContactsBook, 'friends.mars.0'); print_r($myContactsBook['friends']['mars']); // Outputs: Empty array unsetNestedValue($myContactsBook, 'relatives.0'); print_r($myContactsBook['relatives']); // Outputs: Array ( [1] => john )
Quick Notes
- If you want stricter behavior (like throwing exceptions when paths don't exist), you can replace the
return nullor early exits withthrow new InvalidArgumentException("Path does not exist"). - The functions handle both associative keys (like
'relatives') and numeric indexes (like0) seamlessly.
内容的提问来源于stack exchange,提问作者Dwarf Vader

