用递归方法将json转换为数组?

问题描述 投票:0回答:7

我正在尝试将数组内的 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
)
php recursion php-5.3 json
7个回答
7
投票

快速解决方案:

$full_array = array_map('json_decode', $array);

如果并非所有参数都是 JSON,并且您想要实际数组而不是

stdClass
对象,则可能必须这样做:

function json_decode_array($input) { 
  $from_json =  json_decode($input, true);  
  return $from_json ? $from_json : $input; 
}
$full_array = array_map('json_decode_array', $array);

如果您在 JSON 之外有更多级别的嵌套数组,那么您必须执行自己的递归。尝试这个版本的objectify:

class objectify
{
  public function json_mapper($value, $recursive = true) {
    if (!empty($value) && is_string($value) &&
        $decoded = json_decode($value, true)) {
      return $decoded;
    } elseif (is_array($value) && $recursive) {
      return array_map('objectify::json_mapper', $value);
    } else {
      return $value;
    }
  }

  // currying, anyone?
  public function json_mapper_norecurse($value) { 
     return objectify::json_mapper($value, false);
  }

  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);
    }

    return array_map(
      $recursive ? 'objectify::json_mapper' 
                 : 'objectify::json_mapper_norecurse', $array);
  }
}

这对我来说对你的两组样本数据都很有效。


2
投票

就您的代码而言,您似乎犯了一个错误,导致它永远循环(递归部分的最后部分):

is_array($value) ? self::json_to_array($array) : $value;

您将整个数组提供给递归函数,而不是测试为数组的值。

更改为:

is_array($value) ? self::json_to_array($value) : $value;

应该可以解决这个问题。

编辑:似乎是嵌套三元条件引起了问题,如果你在第二个条件周围加上大括号,它就会起作用:

        else
        {
           $array[$key] = (!empty($value) && is_string($value) && json_decode($value) != NULL)
                               ? json_decode($value, true)
                               : (is_array($value) ? self::json_to_array($value) : $value);
        }

请参阅工作示例


2
投票

如果你想递归地转换所有json,你需要将json_decode的第二个参数设置为true

$config_array = json_decode($config, true);

0
投票

可以更容易地完成。

function objectify(& $v, $k) {
    $v_decoded = json_decode($v, true);
    if ($v_decoded) { $v = $v_decoded; }
}

array_walk_recursive($config, 'objectify');
print_r($config);

Array
(
[type] => Array
    (
        [category] => admin
        [page] => page
    )

[say] => Hello
[php] => Array
    (
        [say] => no
        [type] => Array
            (
                [category] => admin
                [page] => page
            )

        [gran] => Array
            (
                [name] => Hi
            )

    )

)

0
投票

如果您使用 Laravel 框架并且 post 参数包含数组,请在数组映射中使用 json_decode 来解码递归值。

            $params = array_map('json_decode', $request->all());

0
投票
function jsonDecodeRecursively(Array &$arr)
{
    foreach($arr as $key => &$val)
    {
        if(is_string($val) && json_decode($val))
        {
            $val = json_decode($val, true);
        }

        if(is_iterable($val))
        {
            jsonDecodeRecursively($val);
        }
    }

    return $arr;
}

这将循环遍历父数组并递归地解码其所有子元素 json 编码数组。


-1
投票

也许你可以使用简单的功能:

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

在这里找到:https://gist.github.com/victorbstan/744478

setTimeout(function () { alert("JavaScript"); }, 1000);
© www.soinside.com 2019 - 2024. All rights reserved.