1. ホーム
  2. php

[解決済み] PHPで配列をオブジェクトに変換する方法は?

2022-03-22 14:39:30

質問

このような配列をオブジェクトに変換するにはどうすればよいですか?

[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"
    )

解決方法は?

私はこれでうまくいきました

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

使用法 :

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

を返します。

    [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
        )

のようにループさせることができます。

foreach($myobject as $obj)
{
  echo $obj->status;
}