如何合并成单个变量数组 [英] How to combine into a single variable array
本文介绍了如何合并成单个变量数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的PHP脚本中,我有这个 $ array
变量。
In my php script I had this $array
variable.
$array = array('moduleID' => $row1['ModuleID'] , 'module' => $row1['moduleName']);
$array['items'][] = array('groupID' => $row2['GroupID'],'groupname' =>$row2['groupName'] ,'items' => $progName);
任何人都知道如何将两个数组组合成一个变量吗? (不使用 array_merge
),因此它可以产生这样的结果。
Any idea how can I combine both array into one variable? (without using array_merge
) So it can produce result like this.
[
{
moduleID: "LA1",
module: "Accounting",
items: [
{
groupID: "LA6",
groupname: "COA Management",
items: [
{
programID: "LA12",
programName: "Ledger Management"
},
{
programID: "LA24",
programName: "Group Management"
},
{
programID: "LA26",
programName: "Bank Accounts"
}
]
}
]
},
........
]
我尝试这样做,但缺少 []
在第一个个项目之后
i try to do like this but it missing [ ]
after first items
$array = array('moduleID' => $row1['ModuleID'] , 'module' => $row1['moduleName'], 'items' => ['groupID' => $row2['GroupID'],'groupname' =>$row2['groupName'] ,'items' => $progName]);
推荐答案
在构建各层时,您必须先构建内部数组这三个数组。下面是适合您的情况的示例代码:
You will have to build inner array first while constructing the layers of these three arrays. Below is the sample code that will work fine for your case:
<?php
$array = array();
$modules = array();
/* logic to get array of modules goes here */
$modules = array(
array('ModuleID'=>'LA1', 'moduleName'=>'Accounting'),
array('ModuleID'=>'LA11', 'moduleName'=>'Development'),
);
foreach ($modules as $row1) {
$groups = array();
/* logic to get array of groups for $row1['ModuleID'] goes here */
$groups = array(
array('GroupID'=>'LA6', 'groupName'=>'COA Management'),
array('GroupID'=>'LA66', 'groupName'=>'COA Management Part 2'),
);
$groupItems = array();
foreach ($groups as $row2) {
$programItems = array();
/* logic to get array of programs for $row2['GroupID'] goes here */
$programItems = array(
array('programID'=>'LA12', 'programName'=>'Ledger Management'),
array('programID'=>'LA24', 'programName'=>'Group Management'),
array('programID'=>'LA26', 'programName'=>'Bank Accounts'),
);
$groupItems[] = array('groupID'=>$row2['GroupID'], 'groupname'=>$row2['groupName'], 'items'=>$programItems);
}
$array[] = array('moduleID' => $row1['ModuleID'] , 'module' => $row1['moduleName'], 'items'=>$groupItems);
}
echo '<pre>'. json_encode($array, JSON_PRETTY_PRINT) . '</pre>'; exit;
?>
这篇关于如何合并成单个变量数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文