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

为前端需求将多维数组转换为一维数组的技术咨询

Flattening Multidimensional Style Array for Frontend Use

Got it, let's turn that nested style array into a flat, frontend-friendly one. The idea is to create a single-level array where each key represents the full nested path of the original property—so something like top_menu.li.a.clr instead of digging through layers of arrays.

First, let's recap your original array for clarity:

$styleArray = [
    'top_menu' => [
        'li' => [
            'a' => ['clr' => '#FF00FF'],
            'a:hover' => ['clr' => '#FF6600']
        ]
    ],
    'wrap-zfcnt' => [
        'a' => ['clr' => '#99CC00'],
        'p' => [
            'ffam' => 'Comic Sans MS',
            'clr' => '#FF0000',
            'fsz' => '9px'
        ],
        'a:hover' => [
            'clr' => '#666699',
            'txtd' => 'underline'
        ]
    ],
    'sidebar-zfcnt' => [
        'bgi' => 'url(/res/uploads/webist/0/3/6815/res/18291/logo.png?1)'
    ]
];

Recursive Function to Flatten the Array

We'll use a recursive function to traverse every nested level, building full path keys as we go. This works for any depth of nesting, which is handy if your style config grows later:

function flattenStyleArray($array, $parentKey = '') {
    $result = [];
    
    foreach ($array as $key => $value) {
        // Build the full key path—use dots to separate levels (adjust if needed)
        $currentKey = $parentKey ? "$parentKey.$key" : $key;
        
        if (is_array($value)) {
            // Recurse into nested arrays
            $result = array_merge($result, flattenStyleArray($value, $currentKey));
        } else {
            // Add the flat key-value pair
            $result[$currentKey] = $value;
        }
    }
    
    return $result;
}

// Usage
$flatStyleArray = flattenStyleArray($styleArray);

Resulting Flat Array

When you run the function, you'll get this clean, frontend-ready array:

[
    'top_menu.li.a.clr' => '#FF00FF',
    'top_menu.li.a:hover.clr' => '#FF6600',
    'wrap-zfcnt.a.clr' => '#99CC00',
    'wrap-zfcnt.p.ffam' => 'Comic Sans MS',
    'wrap-zfcnt.p.clr' => '#FF0000',
    'wrap-zfcnt.p.fsz' => '9px',
    'wrap-zfcnt.a:hover.clr' => '#666699',
    'wrap-zfcnt.a:hover.txtd' => 'underline',
    'sidebar-zfcnt.bgi' => 'url(/res/uploads/webist/0/3/6815/res/18291/logo.png?1)'
]

Quick Notes

  • If you prefer a different separator (like underscores instead of dots) for frontend compatibility, just change the $currentKey line to use $parentKey ? "$parentKey_$key" : $key or whatever you need.
  • The function handles special characters in keys (like a:hover) seamlessly, which is perfect for CSS pseudo-classes.

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

相关产品推荐
方舟 Agent Plan

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

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