在php中将数组转换为对象

时间:2022-12-30 20:21:50

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

我在php中将发布的数据从表单转换为如下对象:

<?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 个解决方案

#1


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

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

#2


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();

使用面向对象的编程,这可能是您正在寻找的。将它视为一个对象,通过创建一个名为Color的类并执行$ colors [$ i] = new Color();

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

这样你就可以用它做任何你想做的事情,并为它添加功能。

#3


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:

非常简单 - 当你将color_type键附加到你的对象时,它将成为一个数组,它是你对象的属性。这很可能是你想要的:你可能不希望将该数组转换为它自己的基于stdClass的对象,因为那时你将无法遍历所有的值(很容易)。这是一个片段:

<?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).

希望这可以帮助!当然,在现实环境中,您需要进行各种数据验证和清理 - 例如,您需要检查浏览器是否实际传递了$ _POST ['color_type'的值数组如果有人试图在你的页面中注入一个漏洞利用,你会想要清理输出(通过回显htmlspecialchars($ thisColor); - 这会将所有像 <和> 这样的字符转换为HTML实体,这样他们就能' t插入JavaScript代码)。

#1


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

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

#2


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();

使用面向对象的编程,这可能是您正在寻找的。将它视为一个对象,通过创建一个名为Color的类并执行$ colors [$ i] = new Color();

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

这样你就可以用它做任何你想做的事情,并为它添加功能。

#3


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:

非常简单 - 当你将color_type键附加到你的对象时,它将成为一个数组,它是你对象的属性。这很可能是你想要的:你可能不希望将该数组转换为它自己的基于stdClass的对象,因为那时你将无法遍历所有的值(很容易)。这是一个片段:

<?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).

希望这可以帮助!当然,在现实环境中,您需要进行各种数据验证和清理 - 例如,您需要检查浏览器是否实际传递了$ _POST ['color_type'的值数组如果有人试图在你的页面中注入一个漏洞利用,你会想要清理输出(通过回显htmlspecialchars($ thisColor); - 这会将所有像 <和> 这样的字符转换为HTML实体,这样他们就能' t插入JavaScript代码)。