如何在Laravel/PHP中创建多维数组 [英] How to create an multidimensional array in Laravel/PHP

查看:81
本文介绍了如何在Laravel/PHP中创建多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些值存储在一个数组中,其中每个元素都有其子元素.

I'm trying to store some values in one array, where each element has its child element.

请找到代码:

$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;
  }
}

我想存储类似child['parent_element']['child_element']的内容 即预期的数组格式

I want to store something like child['parent_element']['child_element'] i.e expected array format

child[1][2]
child[1][3]
child[1][4]
child[1][5]
child[2][6]
child[2][7]
.
.
child[3][12]

帮帮我.谢谢

推荐答案

假设您的表数据为

tblusers

id   name
 1   John
 2   Doe
 3   Carl
 4   Jose
 5   Bill
 6   James
 7   Karl

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 = [];

然后循环您的父数组

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';
}

所以您的代码将是这样

$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;
    }
}

结果将是这样

array(
    [1] => array(
          [2] => 'value',
          [3] => 'value',
          [4] => 'value',
          [5] => 'value',
    ),
    [2] => array(
          [6] => 'value',
          [7] => 'value'
    ),
    etc...
)

或者您可以将'value'留给true

这篇关于如何在Laravel/PHP中创建多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆