php - 使用php循环生成多级关联数组
问题描述
试图从嵌套的 php 循环中为 json 输出生成数组,关于如何完成此操作的任何建议?
这是我正在使用的当前代码
$v_id=0;
$x=0;
$item[] = array();
foreach ($abc as $vm) {
foreach ($vm->activity as $record) {
$item['instruction'] = $record->step;
$item['id'] = $x;
$id++;
}
$v_id++;
}
然而,主循环语句的每个循环都高估了先前的条目
这是所需的输出
steps": [
{
"v_id": 0,
"instruction_steps": [
{
"id": 0,
"instruction": "<p>Select something </p>",
{
"id": 1,
"instruction": "<p>Do something</p>",
}
]
},
解决方案
你需要使用array_push()
$v_id=0;
$steps = array();
foreach ($abc as $vm) {
$item = array();
$item["v_id"] = $v_id;
$instruction_steps = array();
$x=0; // This will reset for each
foreach ($vm->activity as $record) {
$row = array();
$row['id'] = $x;
$row["instruction"] = $record->step;
array_push($instruction_steps, $row); // push to i-steps
$x++;
}
$item["instruction_steps"] = $instruction_steps;
array_push($steps, $item); // push to steps
$v_id++;
}
$response = array();
$response["success"] = true;
$response["steps"] = $steps;
echo json_encode($response);
推荐阅读
- pandas - 在熊猫的行和列中对角复制值?
- flutter - 如何使用复选框在 chart_flutter 中隐藏一行图形?
- android - 通知 startForeground() 第二次不工作
- c++ - 被误解的函数的参数
- python - 有什么方法可以忽略日志文件中的输出并在控制台上打印
- asp.net - ASP.Net MVC Web 应用程序,使用 Chrome 时登录失败,使用 IE 时成功
- php - 根据键将数组拆分为子数组
- c# - 为自定义的 ApplicationUser 模型搭建登录/注册 UI?
- javascript - 如何更改 ng2 图表中特定标签的颜色?
- python - Python:如何检查 XML 字符串是否是有效的 XML