0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSON形式の文字列を連想配列に変換する方法

Posted at

JSON形式の文字列を連想配列にしたい場合、どのように実装するかを簡単にまとめたものになります。

{
  "search": [
    {
      "keyword": "test"
    },
    {
      "keyword": "test1"
    }
  ]
}

上記のJSONを連想配列にする場合、json_decodeを用いることで連想配列に変換することができます。

<?php

$json = '{"search": [{"keyword": "test"},{"keyword": "test1"}]}';

// JSON形式の文字列を連想配列へ変換
$search = json_decode($json, true);

// 確認
var_dump($search);

var_dump の実行結果は以下の通りです。

array(1) {
  ["search"]=>
  array(2) {
    [0]=>
    array(2) {
      ["keyword"]=>
      string(4) "test"
    }
    [1]=>
    array(2) {
      ["keyword"]=>
      string(5) "test1"
    }
  }
}

json_decodeの注意点

json_decode を用いる場合、第二引数にtrueを設定すれば、連想配列を返します。
ただし、第二引数を設定していない、もしくはfalseを設定した場合は、オブジェクトを返します。

ここ最近、DBからJSONの文字列を取得して配列に変換する処理を実装したので、簡単に記事としてまとめました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?