简体   繁体   中英

Array to String conversion error in Symfony2

I have a form from which i am fetching the data as array in controller from $request->get() method and want to submit that data to database..

This is the array i am getting when i print the post variable:

Array
(

[country] => Array
    (
        [0] => 24
        [1] => 4
    )

[state] => Array
    (
        [0] => Cuando Cubango
        [1] => Badakhshan
    )

[activity] => Array
    (
        [0] => 3
        [1] => 5
    )

[activity_0] => Array
    (
        [0] => 3
    )

)

I want them to insert in database in this format:

country state            activity
24      Cuando Cubango   3  
24      Cuando Cubango   5
4       Badakhshan       3

What i have tried so far is this:

$active = $request->get('activity');
if (!empty($active)) {
    foreach ($active as $activity) {
        $states = $request->get('state');
        $c = $request->get('country');
        $Bidactivity = $active;
        foreach ($states as $state) {
            foreach ($Bidactivity as $orgact) {
                $activity_to_db = new Activity();
                $activity_to_db->setActivityid($active);
                $activity_to_db->setState($states);
                $activity_to_db->setBidOrganiser($organiserDetails);
                $activity_to_db->setCountry($c);
                $em->persist($activity_to_db);
                $em->flush();
            }
        }
    }
}

But i am getting the array to string conversion error. Please guide.

You get this error, because you pass an array to every field of your activity:

  $activity_to_db->setActivityid($active); /* is this [activity] => Array
(
    [0] => 3
    [1] => 5
)*/
  $activity_to_db->setState($states); /* is this [state] => Array
(
    [0] => Cuando Cubango
    [1] => Badakhshan
)*/
  $activity_to_db->setBidOrganiser($organiserDetails); // doesn't occure, so whats that
  $activity_to_db->setCountry($c); /* is this [country] => Array
(
    [0] => 24
    [1] => 4
)*/

So anywhere there is the error.

Loop between the array with the highest number of elements as $active = $request->get('activity'); Try the smt like

$states = $request->get('state');
 $c = $request->get('country');
 if (!empty($active)) {
      foreach ($c as $index=> $country) {
        foreach ($states as $state) {
           foreach ($active as $activity) {
            $activity_to_db = new Activity();
            $activity_to_db->setActivityid($activity);
            $activity_to_db->setState($state);
            $activity_to_db->setCountry($country);
            $em->persist($activity_to_db);
          }
        }
      }
 }
 $em->flush();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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