如何在 Laravel/PHP 中创建多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40905044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create an multidimensional array in Laravel/PHP
提问by Nitish Kumar
I'm trying to store some values in one array, where each element has its child element.
我试图将一些值存储在一个数组中,其中每个元素都有其子元素。
Please find the code:
请找到代码:
$children = $user->relations()->wherePlanId($selectplan)->get();
foreach($children as $ch)
{
$child[] = $ch->pivot->child;
$subuser = User::find($ch->pivot->child);
if($subuser){
$subchildren = $subuser->relations()->wherePlanId($selectplan)->get();
foreach($subchildren as $subchild)
{
$subchildid[] = $subchild->pivot->child;
}
}
else
{
$subchildid[] = NULL;
}
}
I want to store something like child['parent_element']['child_element']
i.e expected array format
我想存储类似child['parent_element']['child_element']
ie 预期数组格式的东西
child[1][2]
child[1][3]
child[1][4]
child[1][5]
child[2][6]
child[2][7]
.
.
child[3][12]
Help me out. Thanks
帮帮我。谢谢
回答by Beginner
Assuming your table data is
假设您的表数据是
tblusers
tblusers
id name
1 John
2 Doe
3 Carl
4 Jose
5 Bill
6 James
7 Karl
tblparents
tblparents
id parent child
1 1 2
2 1 3
3 1 4
4 1 5
5 2 6
6 2 7
First: declare a variable which will store your array
首先:声明一个将存储您的数组的变量
$child_arr = [];
then loop your parent array
然后循环你的父数组
foreach($children as $ch) {
// do something
}
Inside the loop of your parent loop the children your loop parent
在你的父循环的循环中,你的循环父的孩子
foreach($subchildren as $subchild) {
$child_arr['your parent id']['your child id'] = 'your desired value';
}
so your code would be like this
所以你的代码会是这样的
$child_arr = [];
$children = $user->relations()->wherePlanId($selectplan)->get();
foreach($children as $ch) {
$parent_id = $ch->pivot->child;
$subuser = User::find($ch->pivot->child);
if($subuser) {
$subchildren = $subuser->relations()->wherePlanId($selectplan)->get();
foreach($subchildren as $subchild) {
$child_id = $subchild->pivot->child;
$child_arr[$parent_id][$child_id] = $subchild;
}
} else {
$child_arr[$parent_id] = null;
}
}
the result would be like this
结果会是这样
array(
[1] => array(
[2] => 'value',
[3] => 'value',
[4] => 'value',
[5] => 'value',
),
[2] => array(
[6] => 'value',
[7] => 'value'
),
etc...
)
or you can just leave 'value'
to true
或者你可以留下'value'
来true
回答by er.irfankhan11
Try This:
尝试这个:
foreach($children as $ch)
{
$child[] = $ch->pivot->child;
$subuser = User::find($ch->pivot->child);
if($subuser){
$subchildren = $subuser->relations()->wherePlanId($selectplan)->get();
foreach($subchildren as $subchild)
{
$subchildid[$ch->pivot->child] = $subchild->pivot->child;
}
}
else
{
$subchildid[] = NULL;
}
}