2

I have an array of class objects:

class Foo
{
    public $A;
    public $B;
    public $C;
}

I need a new array of C fields. Is there a way to convert the array without explicit loops? Hate that after C#.

// Explicit conversion:
foreach ($arr as $item)
{
    $Cs[] = $item->C;
}

Regards,

noober
  • 4,819
  • 12
  • 49
  • 85

2 Answers2

8
$Cs = array_map(function($item) {
    return $item->C;
}, $arr);
Matěj Koubík
  • 1,087
  • 1
  • 9
  • 25
0

I believe you can use get_object_vars.

$arr = get_object_vars(new Foo());
var_dump($arr); // should give Array(3) { "A"=>NULL, "B"=>NULL, "C"=>NULL }
Prasanth
  • 5,230
  • 2
  • 29
  • 61
  • Yep, but $arr is array of Foo, not a single instance. Also, I'll have to filter the resulting array from As and Bs. – noober Oct 02 '12 at 10:37