41
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

php 多次元配列になったstdClassをArrayにキャストする

Last updated at Posted at 2017-04-20

背景

これを

[
        (int) 0 => object(stdClass) {
                id => 1
                name => 'taro'
        },
        (int) 1 => object(stdClass) {
                id => 2
                name => 'jiro'
        }
]

こうしたい

[
        (int) 0 => [
                'id' => 1,
                'name' => 'taro',
        ],
        (int) 1 => [
                'id' => 2,
                'name' => 'jiro',
       ]
] 

環境

$ php -v
PHP 5.6.14 (cli) (built: Sep 30 2015 14:07:43)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

結果

これだけ

$array = json_decode(json_encode($stdArray), true);

やっていることは単純で一度jsonにエンコードした後、配列形式にデコードしている。
json_decode の第二引数に true を指定することで配列形式にデコードしてくれる。

参考にさせて頂いたURL

http://php.net/manual/ja/function.json-encode.php
http://php.net/manual/ja/function.json-decode.php

41
41
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?