1

In php I am converting posted data from a form to objects like this:

<?php

...some code...

    $post = new stdClass;

    foreach ($_POST as $key => $val)
        $post->$key = trim(strip_tags($_POST[$key]));

?>

Then in my page I just echo posted data like this :

<?php echo $post->Name; ?>
<?php echo $post->Address; ?>

etc...

This works fine but I have multiple checkboxes that are part of a group and I echo the results of that, like this:

<?php
  $colors = $_POST['color_type'];
  if(empty($colors))
  {
    echo("No color Type Selected.");
  }
  else
  {
    $N = count($colors);

     for($i=0; $i < $N; $i++)
    {
      echo($colors[$i] . ", ");
    }
  }
?>

That works when I am just using array, but how do I write this as object syntax?

3 Answers 3

3

using your code

function array_to_object($arr) {
    $post = new stdClass;
    foreach ($arr as $key => $val) {
        if(is_array($val)) {
            $post->$key = post_object($val);
        }else{
            $post->$key = trim(strip_tags($arr[$key]));
        }
    }
    return $post;
}

$post = array_to_object($_POST);

or more complex solution

function arrayToObject($array) {
    if(!is_array($array)) {
        return $array;
    }

    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
      foreach ($array as $name=>$value) {
         $name = strtolower(trim($name));
         if (!empty($name)) {
            $object->$name = arrayToObject($value);
         }
      }
      return $object;
    }
    else {
      return FALSE;
    }
}

from http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass

Sign up to request clarification or add additional context in comments.

Comments

0

why would you want that? What's wrong with an array?

Use Object Oriented Programming, which might be what you are looking for. Treat it as an object, by making a class called Color and doing $colors[$i] = new Color();

This way you can do whatever you want with it, and add functions to it.

Comments

0

Pretty simple -- when you attach the color_type key to your object, it'll become an array that's a property of your object. This is most likely what you want: you probably won't want to turn that array into its own stdClass-based object, because then you won't be able to iterate through all the values (as easily). Here's a snippet:

<?php
    // putting in both of these checks prevents you from throwing an E_WARNING
    // for a non-existent property. E_WARNINGs aren't dangerous, but it makes
    // your error messages cleaner when you don't have to wade through a bunch
    // of E_WARNINGS.
    if (!isset($post->color_type) || empty($post->color_type)) {
        echo 'No colour type selected.'; // apologies for the Canadian spelling!
    } else {
        // this loop does exactly the same thing as your loop, but it makes it a
        // bit more succinct -- you don't have to store the count of array values
        // in $N. Bit of syntax that speeds things up!
        foreach ($post->color_type as $thisColor) {
            echo $thisColor;
        }
    }
?>

Hope this helps! Of course, in a real-life setting, you'll want to do all sorts of data validation and cleaning -- for instance, you'll want to check that the browser actually passed an array of values for $_POST['color_type'], and you'll want to clean the output in case someone is trying to inject an exploit into your page (by going echo htmlspecialchars($thisColor); -- this turns all characters like < and > into HTML entities so they can't insert JavaScript code).

3 Comments

this sounds closer to what I think I am looking for. my page already worked the way I wanted by taking all the posted data and just echoing it on the page as described like <?php echo $post->Name; ?> However, I didn't know how to get the checkbox group in the same object format as the other info that is posted. But, I am keeping count because a user may seclect more than one option and there are about 20 options. Also, the output was comma separated (which I wanted) when it is displayed on the page. I have not got to try your solution yet, but will this still work for me?
I am very very new to php ... so I was hoping there was a way I could understand to just take what I had explained in the second part of the original question that worked when its posted as an Array and instead make it objects like the rest of the info that is being echoed. Something like <?php $colors = $post->color_type; if(empty($colors)) { echo("No color Type Selected."); } else { $N = count($colors); for($i=0; $i < $N; $i++) { echo($colors[$i] . ", "); } } ?> that obviously doesnt work...but I was hoping it was along those lines.
To answer the comma-separated question, that's real easy. Just throw out the for loop and replace it with echo implode(', ', $colors); -- the first argument is the glue (in this case a comma and a space) and the second argument is the array that you want to 'implode' (or glue all the elements together into one string). Is there any particular reason you need the colours to be an object or objects, rather than just an array? Arrays are generally easier to manipulate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.