【问题标题】:How to create an multidimensional array in Laravel/PHP如何在 Laravel/PHP 中创建多维数组
【发布时间】:2017-04-15 18:15:32
【问题描述】:

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

请查找代码:

$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'] 的东西 即预期的数组格式

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

帮帮我。谢谢

【问题讨论】:

  • 您期望的数组格式是什么?
  • 你的$children的结构是什么?
  • 每个索引child['parent_element']['child_element']的值应该是多少?

标签: php arrays laravel multidimensional-array laravel-5.3


【解决方案1】:

假设你的表格数据是

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

首先:声明一个存储数组的变量

$child_arr = [];

然后循环你的父数组

foreach($children as $ch) {
    // do something
}

在父循环的循环中,子循环父循环

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

    • 它与数组值重叠,只显示最后一个值!
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2015-06-16
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多