LoginSignup
1
1

More than 5 years have passed since last update.

json_decodeで作ったオブジェクトを配列にキャストしたらハマった

Last updated at Posted at 2016-11-15

PHP5.6.27にて以下のコードを書いたら困ったことになった。

>>> $a = (array)json_decode('{"0":"test"}')
=> [
     "0" => "test",
   ]
>>> $a[0]
PHP error:  Undefined offset: 0 on line 1
>>> $a["0"]
PHP error:  Undefined offset: 0 on line 1

$aの中身が取り出せない…。
キャスト使うこと自体が悪手なのだとは思うけど、とりあえずarray_valuesを使って対処した。

>>> $a = array_values($a)
=> [
     "test",
   ]
>>> $a[0]
=> "test"
>>> $a["0"]
=> "test"
1
1
6

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
1
1