0

I have an object named Property, how can I convert that to array

/**
 * @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

saravana
  • 311
  • 4
  • 14
  • Possible duplicate of [Symfony2: Convert retrieved objects to array (and dumping variables for troubleshooting)](http://stackoverflow.com/questions/20653870/symfony2-convert-retrieved-objects-to-array-and-dumping-variables-for-troubles) – STaefi Mar 07 '16 at 07:58

2 Answers2

0

What is pictures?

In simple cases you can use (array) $pictures.

Also, you can use 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.

Try:

$compressPath = $this->get('some_service.property.picture_compress')->compress(iterator_to_array($pictures));
Arthur
  • 2,869
  • 14
  • 25
0

This is how I turned my model MyObject object into a data array.

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));
Hau Le
  • 191
  • 1
  • 4