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,649
  • 12
  • 48
  • 83

2 Answers2

8
$Cs = array_map(function($item) {
    return $item->C;
}, $arr);
Matěj Koubík
  • 1,004
  • 1
  • 8
  • 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,109
  • 2
  • 27
  • 59
  • 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