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

CodeIgniter模板解析器:如何将多维$this->data数组转为一维数组

多维数组转一维数组的解决方案

嘿,这个需求在PHP开发里挺常见的,咱们用递归函数就能轻松搞定,不管数组嵌套多少层都能完美处理。我分两种场景给你说明:

基础版:直接扁平化(覆盖重复键)

针对你给出的数组结构,这个递归函数刚好能满足需求:

function flattenArray($array) {
    $flattened = [];
    foreach ($array as $key => $value) {
        // 如果当前元素是子数组,递归处理后合并到结果集
        if (is_array($value)) {
            $flattened = array_merge($flattened, flattenArray($value));
        } else {
            // 普通值直接存入结果数组
            $flattened[$key] = $value;
        }
    }
    return $flattened;
}

// 调用示例
$flattenedData = flattenArray($this->data);
print_r($flattenedData);

运行后就能得到你想要的一维数组:

Array ( 
    [icon] => http://localhost/uploads/icon.png 
    [logo] => http://localhost/uploads/logo.svg 
    [canonical] => http://localhost/profile/register/ 
    [title] => Register 
)

进阶版:保留层级前缀(避免键冲突)

如果你的数组里存在重复键名(比如不同嵌套层都有title键),上面的方法会覆盖之前的值。这时候可以给子键加上父键前缀,比如seo_title,修改后的函数如下:

function flattenArrayWithPrefix($array, $parentPrefix = '') {
    $flattened = [];
    foreach ($array as $key => $value) {
        // 拼接前缀和当前键名
        $currentKey = $parentPrefix ? "{$parentPrefix}_{$key}" : $key;
        if (is_array($value)) {
            $flattened = array_merge($flattened, flattenArrayWithPrefix($value, $currentKey));
        } else {
            $flattened[$currentKey] = $value;
        }
    }
    return $flattened;
}

// 调用示例
$flattenedData = flattenArrayWithPrefix($this->data);
print_r($flattenedData);

这时候输出会变成:

Array ( 
    [icon] => http://localhost/uploads/icon.png 
    [logo] => http://localhost/uploads/logo.svg 
    [seo_canonical] => http://localhost/profile/register/ 
    [seo_title] => Register 
)

这个方法扩展性极强,不管你的数组嵌套多少层(比如seo里再套一个meta子数组),都能自动处理成一维结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:25:40