You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现多维数组指定路径元素的读取、修改与删除功能

Working with Nested Array Members via Path Parameters

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 null or early exits with throw new InvalidArgumentException("Path does not exist").
  • The functions handle both associative keys (like 'relatives') and numeric indexes (like 0) seamlessly.

内容的提问来源于stack exchange,提问作者Dwarf Vader

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:23:19