配列内のjson文字列を配列に変換しようとしています。
$config = array(
"type" => '{"category":"admin","page":"page"}',
"say" => "Hello",
"php" => array(
"say" => "no",
"type" => '{"category":"admin","page":"page"}',
"gran" =>array(
"name" => "Hi"
)
)
);
私の作業コード、
class objectify
{
public function json_to_array($array, $recursive = true)
{
# if $array is not an array, let's make it array with one value of former $array.
if (!is_array($array)) $array = array($array);
foreach($array as $key => $value)
{
if($recursive === false) $array[$key] = (!empty($value) && is_string($value) && json_decode($value) != NULL) ? json_decode($value, true): $value;
else $array[$key] = (!empty($value) && is_string($value) && json_decode($value) != NULL) ? json_decode($value, true): is_array($value) ? self::json_to_array($array) : $value;
}
return $array;
}
}
再帰メソッドがなく ても正常に動作しますが、上記のコードでわかるように、再帰を実行したい場合は機能しません。
$object = new objectify();
$config = $object->json_to_array($config);
print_r($config);
エラーメッセージ、
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 2048 bytes) in C:\wamp\www\test\2012\php\set_variable.php on line 79
この結果を得たいだけです、
Array
(
[type] => Array
(
[category] => admin
[page] => page
)
[say] => Hello
(
[say] => no
[type] => {"category":"admin","page":"page"}
[gran] => Array
(
[name] => Hi
)
)
)
編集:
$config = 'type={"category":"admin","page":"page"}&text_editor={"name":"mce-basic"}&parent_id=self&subtitle=true&description=true&content_1=true&script_1=true&primary_image=true';
parse_str($config,$array);
print_r($array);
結果、
Array
(
[type] => {"category":"admin","page":"page"}
[text_editor] => {"name":"mce-basic"}
[parent_id] => self
[subtitle] => true
[description] => true
[content_1] => true
[script_1] => true
[primary_image] => true
)