php - 转换 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
}
]
}
]
我尝试编写不同的迭代解决方案,但无法获得这种类型的解决方案,并且在迭代方面非常复杂。
解决方案
您可以通过以 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 和此堆栈溢出问题上阅读更多相关信息。
推荐阅读
- databricks - 从 UI 下载任务 StdOut 输出
- sharepoint - 尝试通过第 3 方连接器连接到 SharePoint Online 获取密码与...错误中的一个不匹配
- python - discord.py - 已经存在的命令或别名无缘无故地重复
- c++ - 在类型转换为数据类型时弹出随机值
- pine-script - 并非所有订单都在交易视图 pinescript 策略中执行
- rust - 特征向下转换
- angular - 一个 @ngrx/effect 中的多个 Http 调用
- .net-core - DbContext.BeginTransactionAsync 有时需要几秒钟才能完成
- java - 如何为检查点建立JPA谓词属于给定的多边形
- struct - 如何在调试输出中打印完整的结构路径?