简体   繁体   English

如何将对象转换为数组Symfony2

[英]how to convert object to array Symfony2

I have an object named Property, how can I convert that to array 我有一个名为Property的对象,如何将其转换为数组

/**
 * @Route("/property/{id}/pictures/download_all", name="property_zip_files_and_download", methods={"GET"})     
 */
public function zipFilesAndDownloadAction(Property $property)
{
    $pictures = $property->pictures;
$compressPath = $this->get('some_service.property.picture_compress')->compress($pictures);
//some code for download...
....
}

How can I convert the pictures to array and pass it to my service? 如何将图片转换为数组并将其传递给我的服务? Can anyone please help me out here 有人可以帮我吗

What is pictures? 什么是图片?

In simple cases you can use (array) $pictures . 在简单的情况下,您可以使用(array) $pictures

Also, you can use Serializer Normalizers 另外,您可以使用Serializer Normalizers

if variable is Iterator (ArrayCollection or PersistentCollection for example) and service method has array as typehinting, you can convert it to simple array with iterator_to_array function. 如果变量是Iterator (例如ArrayCollection或PersistentCollection)并且服务方法将array作为类型提示,则可以使用iterator_to_array函数将其转换为简单数组。

Try: 尝试:

$compressPath = $this->get('some_service.property.picture_compress')->compress(iterator_to_array($pictures));

This is how I turned my model MyObject object into a data array. 这就是我将模型MyObject对象变成数据数组的方式。

class MyObject{

    public function getContentArr($objInstance, $filter=true){

        $arr = array();

        if($objInstance){
            $response = new Response(GeneralFunctions::getKernel()->getContainer()->get('serializer')->serialize($objInstance, 'json'));

            $arr = json_decode($response->getContent(), true);

            //remove all items that are null, or empty string
            //if($filter){
               //$arr = $this->filterContentArr($arr); // optional
            //}
        }        

        return $arr;
    }

    /**
     * Returns filtered array removing empty/null
     * 
     * @param array $data
     * @return array
     */
    public function filterContentArr($data){               
        foreach($data as $key => $val){
            if(is_array($val)){

                $data[$key] = $this->filterContentArr($val);

                if(empty($data[$key])){
                    unset($data[$key]); //remove empty array
                }

            }else{
                if($val == "" || $val == null){
                    unset($data[$key]);
                }
            }
        }

        return $data;
    }
}

$myObject = new MyObject();
print_r($myObject->getContentArr($myObject));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM