如何正确映射对象数组

时间:2020-02-07 15:00:08

标签: php arrays

我有以下对象数组($grow):

class ArrayObject#48 (1) {
  private $storage =>
  array(4) {
    [0] =>
    class stdClass#84 (3) {
      public $id =>
      string(5) "1"
      public $name =>
      string(5) "dasdasd"
      public $pimba =>
      string(2) "kl"
    }
    [1] =>
    class stdClass#46 (3) {
      public $id =>
      string(5) "2"
      public $name =>
      string(5) "sadwqq"
      public $pimba =>
      string(2) "kl"
    }
    [2] =>
    class stdClass#83 (3) {
      public $id =>
      string(5) "3"
      public $name =>
      string(5) "bbbbbb"
      public $pimba =>
      string(2) "kl"
    }
    [3] =>
    class stdClass#43 (3) {
      public $id =>
      string(5) "3"
      public $name =>
      string(5) "aaaaaa"
      public $pimba =>
      string(2) "kl"
  }
}

我无法使用array_map,它总是返回 null 。我认为是因为private $storage,但我不知道如何解决。

array_push($arr, array_map(function($c) {
    return $c;
},$grow));

2 个答案:

答案 0 :(得分:4)

array_map需要一个数组作为第二个参数。您正在向其传递ArrayObject

您将要使用iterator_to_array将该对象(它是迭代器,因为它实现了Traversable)转换为数组:

array_map(function ($c) {
  // ... do stuff with $c
  return $c;
}, iterator_to_array($grow))

旁注:您应该使用$array[] = $value;而不是array_push($array, $value);,因为它既方便又快捷。

顺便说一句,在这种情况下,我不确定您是否要插入阵列。这会将子数组添加到您现有的$arr数组中。根据您的尝试,array_merge可能就是您想要的。

答案 1 :(得分:1)

您可以尝试这种方式:

with newt as (
      select t.*,
             coalesce(n1,
                      (max(n1) over () +
                       row_number() over (partition by n1 order by a1)
                      )
                     ) as new_n1
      from t
     )
select newt.*, tp.new_n1 as parent_n1
from newt left join
     newt newtp
     on newt.p1 = newtp.a1;

您可以选中此Doc。希望能帮到您。