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

PHP数组键字符串化及JSON键提取:优化可复用递归函数需求

Hey there! Let's tackle your PHP array key handling needs with a clean, reusable recursive solution that's way more maintainable than repetitive nested loops.

递归扁平化数组键:优雅收集所有层级的键值

核心需求回顾

You're looking to:

  1. Convert all keys (including nested subarray keys) in a PHP array to strings, with child keys appended to their parent keys (e.g., parent.child)
  2. Replace redundant traversal code with a reusable function that works for dynamically changing JSON data sources (like category data)

优化后的递归实现

This recursive function handles arbitrarily deep nested arrays, supports custom separators, and perfectly adapts to your dynamic data needs:

function flattenArrayKeys(array $array, string $parentKey = '', string $separator = '.'): array {
    $keys = [];
    
    foreach ($array as $key => $value) {
        // Combine parent key with current key, ensuring all keys are string type
        $currentKey = $parentKey ? "{$parentKey}{$separator}{$key}" : (string)$key;
        
        // Recursively process subarrays and merge results
        if (is_array($value)) {
            $keys = array_merge($keys, flattenArrayKeys($value, $currentKey, $separator));
        } else {
            // Record the full key path for non-array values
            $keys[] = $currentKey;
        }
    }
    
    return $keys;
}

Why this solution works better

  • Dynamic data ready: No matter how many layers your JSON array has, recursion will automatically traverse every level
  • Highly reusable: Define it once, use it for any array scenario—no more copying nested loops
  • Flexible customization: Adjust the key separator via the $separator parameter (swap . for _, /, or anything else)
  • Type safe: Automatically converts all keys to strings, avoiding issues with numeric keys

Example usage (category data scenario)

Suppose your decoded JSON looks like this category array:

$categoryData = [
    'id' => 1,
    'name' => 'Electronics',
    'children' => [
        [
            'id' => 2,
            'name' => 'Phones',
            'children' => [
                'id' => 3,
                'name' => 'Smartphones'
            ]
        ],
        [
            'id' => 4,
            'name' => 'Computers'
        ]
    ]
];

Call the function and print the result:

$flattenedKeys = flattenArrayKeys($categoryData);
print_r($flattenedKeys);

You'll get a list of full key paths across all levels:

Array
(
    [0] => id
    [1] => name
    [2] => children.0.id
    [3] => children.0.name
    [4] => children.0.children.id
    [5] => children.0.children.name
    [6] => children.1.id
    [7] => children.1.name
)

Extra tweaks for your use case

  • Keep key-value pairs: If you need to retain the value alongside each key path, change $keys[] = $currentKey; to $keys[$currentKey] = $value;
  • Remove duplicate keys: Add return array_unique($keys); at the end of the function to eliminate duplicate paths
  • Handle JSON objects: If your JSON decodes to objects instead of arrays, replace is_array($value) with is_iterable($value) to support object traversal

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:06:45