PHP. Is it possible to use array_column with an array of objects

后端 未结 6 1431
一个人的身影
一个人的身影 2020-12-01 03:41

Is it possible to pass in array_column an array of objects?
I have implemented ArrayAccess interface, but it has no effect.
Should I implement another

6条回答
  •  情话喂你
    2020-12-01 03:48

    Is it possible to pass in array_column an array of objects?

    PHP 7

    Yes, see http://php.net/manual/en/function.array-column.php

    PHP 5 >= 5.5.0

    In PHP 5 array_column does not work with an array of objects. You can try with:

    // object 1
    $a = new stdClass();
    $a->my_string = 'ciao';
    $a->my_number = 10;
    
    // object 2
    $b = new stdClass();
    $b->my_string = 'ciao b';
    $b->my_number = 100;
    
    // array of objects
    $arr_o = array($a,$b);
    
    // using array_column with an array of objects
    $result = array_column(array_map(function($o){return (array)$o;},$arr_o),'my_string');
    

    PS: for clarity I prefer to not use array_column and use array_map with an anonymous function

    $result = array_map(function($o){ return $o->my_string; }, $arr_o);
    

    or a simple foreach

    $result = array();
    foreach($arr_o as $o) {
        $result[] = $o->my_string;
    }
    

提交回复
热议问题