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

后端 未结 6 1408
一个人的身影
一个人的身影 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 04:08

    While it's not possible to use array_column on child-objects, you can cast them to arrays. This is of course not the way to go, but it's a way.

    Using array_map/get_object_vars (doesn't not work in your case, due the containing array)

    array_column(array_map('get_object_vars', $thingy), 'property');
    

    Using json_decode/json_encode

    array_column(json_decode(json_encode($thingy), true), 'property');
    

    https://eval.in/597950

    Note: Using json brings not the same result as using a true recursive function. You’ll lose protected and private properties of the object. But in some situations its fine.

    function object_to_array($object) {
      if (is_object($object)) $object = get_object_vars($object);
      return is_array($object) ? array_map(__FUNCTION__, $object) : $object;
    }

提交回复
热议问题