How to convert an array to object in PHP?

2018-12-31 07:56发布

How can i convert an array like this to object?

    [128] => Array
        (
            [status] => Figure A.
 Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.
        )

    [129] => Array
        (
            [status] => The other day at work, I had some spare time
        )

)

30条回答
无与为乐者.
2楼-- · 2018-12-31 08:40

CakePHP has a recursive Set::map class that basically maps an array into an object. You may need to change what the array looks like in order to make the object look the way you want it.

http://api.cakephp.org/view_source/set/#line-158

Worst case, you may be able to get a few ideas from this function.

查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 08:41

Easy:

$object = json_decode(json_encode($array));

Example:

$array = array(
    'key' => array(
        'k' => 'value',
    ),
    'group' => array('a', 'b', 'c')
);

$object = json_decode(json_encode($array));

Then, the following is true:

$object->key->k === 'value';
$object->group === array('a', 'b', 'c')
查看更多
无色无味的生活
4楼-- · 2018-12-31 08:43

This one worked for me

  function array_to_obj($array, &$obj)
  {
    foreach ($array as $key => $value)
    {
      if (is_array($value))
      {
      $obj->$key = new stdClass();
      array_to_obj($value, $obj->$key);
      }
      else
      {
        $obj->$key = $value;
      }
    }
  return $obj;
  }

function arrayToObject($array)
{
 $object= new stdClass();
 return array_to_obj($array,$object);
}

usage :

$myobject = arrayToObject($array);
print_r($myobject);

returns :

    [127] => stdClass Object
        (
            [status] => Have you ever created a really great looking website design
        )

    [128] => stdClass Object
        (
            [status] => Figure A.
 Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.
        )

    [129] => stdClass Object
        (
            [status] => The other day at work, I had some spare time
        )

like usual you can loop it like:

foreach($myobject as $obj)
{
  echo $obj->status;
}
查看更多
人间绝色
5楼-- · 2018-12-31 08:43

I would definitly go with a clean way like this :

<?php

class Person {

  private $name;
  private $age;
  private $sexe;

  function __construct ($payload)
  {
     if (is_array($payload))
          $this->from_array($payload);
  }


  public function from_array($array)
  {
     foreach(get_object_vars($this) as $attrName => $attrValue)
        $this->{$attrName} = $array[$attrName];
  }

  public function say_hi ()
  {
     print "hi my name is {$this->name}";
  }
}

print_r($_POST);
$mike = new Person($_POST);
$mike->say_hi();

?>

if you submit:

formulaire

you will get this:

mike

I found this more logical comparing the above answers from Objects should be used for the purpose they've been made for (encapsulated cute little objects).

Also using get_object_vars ensure that no extra attributes are created in the manipulated Object (you don't want a car having a family name, nor a person behaving 4 wheels).

查看更多
忆尘夕之涩
6楼-- · 2018-12-31 08:45

You could also use an ArrayObject, for example:

<?php
    $arr = array("test",
                 array("one"=>1,"two"=>2,"three"=>3), 
                 array("one"=>1,"two"=>2,"three"=>3)
           );
    $o = new ArrayObject($arr);
    echo $o->offsetGet(2)["two"],"\n";
    foreach ($o as $key=>$val){
        if (is_array($val)) {
            foreach($val as $k => $v) {
               echo $k . ' => ' . $v,"\n";
            }
        }
        else
        {
               echo $val,"\n";
        }
    }
?>

//Output:
  2
  test
  one => 1
  two => 2
  three => 3
  one => 1
  two => 2
  three => 3
查看更多
牵手、夕阳
7楼-- · 2018-12-31 08:46

Its way to simple, This will create an object for recursive arrays as well:

$object = json_decode(json_encode((object) $yourArray), FALSE);
查看更多
登录 后发表回答