首页 > 解决方案 > 转换 PHP 关联数组

问题描述

我想像这样在 PHP Associate Array 下面进行转换

输入:

array(
        array(
            ""=> "Col A",
            "Row A"=> 5,
            "Row B"=> 2,                 
        ),
        array(
            ""=> "Col B",
            "Row A"=> 4,
            "Row B"=> 5,                  
        ),
        array(
            ""=> "total",
            "Row A"=> 7,     // "A's total"
            "Row B"=> 9,     // "B's total"              
        ),
        array(
            ""=> "average",
            "Row A"=> 3.5,    
            "Row B"=> 4.5,                  
        )
    )

上面的Row是固定的,而Col是动态的。

并且需要将其转换为

输出 :

[
    {
        type: "Row A",
        percent: 7,
        subs: [
                {
                    type: "Col A",
                    percent: 5
                }, 
                {
                    type: "Col B",
                    percent: 2
                }
            ]
    }, 
    {
        type: "Row B",
        percent: 9,
        subs: [
                {
                    type: "Col A",
                    percent: 4
                }, 
                {
                    type: "Col B",
                    percent: 5
                }
            ]
    }
]

我尝试编写不同的迭代解决方案,但无法获得这种类型的解决方案,并且在迭代方面非常复杂。

标签: phparrays

解决方案


您可以通过以 JSON 格式对数组进行编码来做到这一点。

以下是示例代码,以便您更好地理解:

<?php
$names = array(
        array(
            "foo"=> "bar",
        ),
        array(
            "foo"=> "bar",
        ),
        array(
            "foo"=> "bar",
        ),
    );
$namesJSON = json_encode($names);
echo "<pre>";
echo $namesJSON;
echo "</pre>"; 

?> 

这将输出所需的 JSON 数组。希望这能回答你的问题。为了生成所需的 JSON 结构,您可以在JS Fiddle 和堆栈溢出问题上阅读更多相关信息。


推荐阅读