PlayHardGoPro
PlayHardGoPro

Reputation: 2933

How to correctly map through an array of objects

I have this array of objects ($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"
  }
}

I'm unable to use array_map, it's always returning null. I think it's because the private $storage but I don't know how to fix it.

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

Upvotes: 1

Views: 338

Answers (2)

Dmitry Leiko
Dmitry Leiko

Reputation: 4412

You can try this way:

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

You can check this Doc. Hope help you.

Upvotes: 1

Jeto
Jeto

Reputation: 14927

array_map expects an array as its second parameter. You're passing an ArrayObject to it.

You'll want to use iterator_to_array to convert that object (which is an iterator, as it implements Traversable) into an array:

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

Side note: you should use $array[] = $value; instead of array_push($array, $value); as it's both handier and quicker.

By the way, I'm not sure you want to push into your array in this case. This will add a sub-array to your existing $arr array. Depending on what you're attempting to do, array_merge may be what you're looking for.

Upvotes: 4

Related Questions