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

PHP多维数组foreach循环:如何提取嵌套数组并正确输出?

多维数组转指定格式字符串的解决方法

需求说明

需要将以下PHP多维数组:

Array ( 
    [durations] => Array ( 
        [0] => Array ( [months] => 36 ) 
        [1] => Array ( [months] => 48 ) 
    ) 
    [duration_default] => 60 
    [insurance_factor] => 0 
    [lease_factor] => 44 
    [create_fee] => 2500 
)

转换为以下格式的字符串(需正确解析嵌套数组):

"durations":[{"months":"36"},{"months":"48"}],"duration_default":"60","insurance_factor":"0","lease_factor":"0.4637","create_fee":"2500"

之前的错误尝试

使用普通foreach循环时,嵌套数组会被直接输出为字符串"Array",代码如下:

foreach ($post_fields as $key=>$item){
    echo ""$key" : "$item", ";
}

错误输出示例:

data-calc="{"durations" : "Array", "duration_default" : "60", "insurance_factor" : "0.9909", "lease_factor" : "44", "create_fee" : "2500", "frequency" : "month", "min_price" : "2222", "margins" : "Array",

解决方案

方法1:递归处理数组

编写递归函数,判断元素类型,嵌套数组逐层解析:

function formatArrayToStr($arr) {
    $result = [];
    foreach ($arr as $key => $item) {
        $keyStr = """ . $key . """;
        if (is_array($item)) {
            $inner = [];
            foreach ($item as $innerItem) {
                $innerPairs = [];
                foreach ($innerItem as $k => $v) {
                    $innerPairs[] = """ . $k . "":"" . $v . """;
                }
                $inner[] = "{" . implode(",", $innerPairs) . "}";
            }
            $valueStr = "[" . implode(",", $inner) . "]";
        } else {
            $valueStr = """ . $item . """;
        }
        $result[] = $keyStr . ":" . $valueStr;
    }
    return implode(",", $result);
}

// 使用示例
echo formatArrayToStr($post_fields);

方法2:利用JSON函数(最优解)

借助PHP内置的json_encode自动处理嵌套结构,再替换引号为HTML实体:

// 转成JSON字符串
$jsonStr = json_encode($post_fields);
// 替换双引号为"
$targetStr = str_replace('"', '"', $jsonStr);
// 按需去掉JSON首尾的大括号
$targetStr = trim($targetStr, '{}');

echo $targetStr;

该方法无需手动编写递归逻辑,高效且能适配任意层级的嵌套数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:21:07