【PHP】多重クラスの配列化



PHPではライブラリの使用やXMLの読み込みを行った時など多重クラスで返ってくる事があります。

ただ、この状態で帰ってこられるととても使いづらい・・・
foreachなどで順次、内容を取得することも出来ないので困ります。

なので今回は多重クラスを簡単に配列化する方法の紹介。

// サンプル用変数の作成
$class = new StdClass();

// クラス内変数
$class->class_1 = 'class_1';

// クラス内クラス1 変数有り(多重オブジェクト)
$class->class_2 = new StdClass();
$class->class_2->hoge = 'hoge';
$class->class_2->fuga = 'fuga';
$class->class_2->piyo = 'piyo';

// クラス内クラス2 変数なし(多重オブジェクト)
$class->class_3 = new StdClass();

現状のままだと以下のようにオブジェクトで使用しづらい状態。
object(stdClass)#4499 (3) {
  ["class_1"]=>
  string(7) "class_1"
  ["class_2"]=>
  object(stdClass)#4498 (3) {
    ["hoge"]=>
    string(4) "hoge"
    ["fuga"]=>
    string(4) "fuga"
    ["piyo"]=>
    string(4) "piyo"
  }
  ["class_3"]=>
  object(stdClass)#4505 (0) {
  }
}

get_object_varsを使用する
PHPマニュアル:get_object_vars
var_dump(get_object_vars($class));
これで配列化をしてもらえますが、クラス内部のクラスまでは配列化されなくてまだ使いづらい・・・
array(3) {
  ["class_1"]=>
  string(7) "class_1"
  ["class_2"]=>
  object(stdClass)#4498 (3) {
    ["hoge"]=>
    string(4) "hoge"
    ["fuga"]=>
    string(4) "fuga"
    ["piyo"]=>
    string(4) "piyo"
  }
  ["class_3"]=>
  object(stdClass)#4505 (0) {
  }
}


json化する
json_encodeとjson_decodeを使用してPHP変数→JSON→PHP変数にするときれいな配列になります。
PHPマニュアル:json_encode
PHPマニュアル:json_decode
var_dump(json_decode(json_encode($class), true));
array(3) {
  ["class_1"]=>
  string(7) "class_1"
  ["class_2"]=>
  array(3) {
    ["hoge"]=>
    string(4) "hoge"
    ["fuga"]=>
    string(4) "fuga"
    ["piyo"]=>
    string(4) "piyo"
  }
  ["class_3"]=>
  array(0) {
  }
}

多重クラスを配列化するとforやforeachで内部を回せるのでとてもありがたいです。
再帰的にget_object_varsを行う方法もありますが、それはfanctionを作ったりするのが手間なのでjson化する方法が一番簡単でやりやすいです。


Comments
  1. Nice post. I learn something totally new and challenging on websites

  2. I truly appreciate your technique of writing a blog. I added it to my bookmark site list and will

  3. There is definately a lot to find out about this subject. I like all the points you made

  4. Pretty! This has been a really wonderful post. Many thanks for providing these details.

  5. Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.

  6. I’m often to blogging and i really appreciate your content. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for brand spanking new information.

  7. I like the efforts you have put in this, regards for all the great content.

  8. Your blog post had me hooked from the first sentence.

コメントを残す