dpzjl68484 2016-12-01 07:39
浏览 161
已采纳

如何在Laravel / PHP中创建多维数组

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[1][2]
child[1][3]
child[1][4]
child[1][5]
child[2][6]
child[2][7]
.
.
child[3][12]

Help me out. Thanks

  • 写回答

2条回答 默认 最新

  • duanmei1930 2016-12-01 08:20
    关注

    Assuming your table data is

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

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办