json_decode将空数组转换为字符串

时间:2015-10-02 18:06:40

标签: php arrays json

我有json元素

{"element":{},
 "gallery":{
    "images":[
    {"id":"1","description":{},"image_path":"1.jpg"},
    {"id":"2","description":"Test","image_path":"2.jpg"}
    ]},
 "additional_value":"Test"}

php函数json_decode($ json,TRUE)返回

Array
(
    [element] => Array()
    [gallery] => Array(
            [images] => Array(
                    [0] => Array(
                            [id] => 1
                            [description] => Array()
                            [image_path] => 1.jpg)
                    [1] => Array(
                            [id] => 2
                            [description] => Test
                            [image_path] => 2.jpg)
                    )
             )
    [additional_value] => Test
)

如何将空数组替换/转换为字符串?例如:

 [0] => Array([id] => 1
              [description] => ""
              [image_path] => 1.jpg)

谢谢!

2 个答案:

答案 0 :(得分:3)

我认为最好的方法似乎是(但不是!)解码json并使用array_walk_recursive将空数组转换为空字符串。

此函数以递归方式遍历数组的所有项。它们中的每一个都通过引用传递给指定的回调函数。

然而,事实证明,此函数不会为自身数组的项调用回调,而只调用这些数组中的项。此行为使得无法使用array_walk_recursive找到空数组。

因此,我编写了一个应该完全相同的替换函数,除了在深入递归之前它总是还调用自身为数组的项的回调。

可以在下面找到该功能和调用代码。

<?php
// The replacement function for array_walk_recursive()
function my_array_walk_recursive(&$array, $callback, $userdata = null) {
  if (!is_array($array)) return false;

  foreach ($array as $key => &$value) {
    // Difference: PHP's array_walk_recursive will only call the callback
    // for items that are not arrays themselves. Here, the callback is always called.
    call_user_func_array($callback, array(&$value, $key, $userdata));
    if (is_array($value)) {
      my_array_walk_recursive($value, $callback, $userdata);
    }
  }
  return true;
}

// The calling code.
$json = 
  '{"element":{},
   "gallery":{
      "images":[
      {"id":"1","description":{},"image_path":"1.jpg"},
      {"id":"2","description":"Test","image_path":"2.jpg"}
      ]},
   "additional_value":"Test"}';

$yourArray = json_decode($json, TRUE);

my_array_walk_recursive(
  $yourArray, 
  function(&$item, $key){
    if (is_array($item) && count($item) === 0) {
      $item = "x";
    }
  });

var_dump($yourArray);

答案 1 :(得分:0)

正确的工作下一个代码/技巧

$json_upd = str_replace('{}', '""', $json);
$result = json_decode($json_upd,TRUE);

如果有人有更好的解决方案,请添加评论 - 我将不胜感激。