使用PHP从JSON中删除空项

时间:2018-02-12 08:44:32

标签: php json

我设法合并了JSON文件,并在StackOverflow的帮助下也从我的JSON中删除了特定的项目(名称)。我想从我的JSON文件中删除空项(值)以减小它的大小。我尝试从数组中删除空项目,但无法设法使代码工作。这是不删除项目的代码。

示例JSON:https://pastebin.com/4QsRn32d

$sets = array();
foreach ($urls as $url)
{
    $json = file_get_contents($url);
    $data = json_decode($json, true);
    foreach ($data as $key => $innerObject) {
        if (isset(
                $innerObject['SPEC_Bullet point 1'],
                $innerObject['SPEC_Bullet point 2'],
                $innerObject['SPEC_Bullet point 3']
        )) {
            unset(
                $data[$key]['SPEC_Bullet point 1'],
                $data[$key]['SPEC_Bullet point 2'],
                $data[$key]['SPEC_Bullet point 3']
            );
        }
    }
    $json = substr($json, 1, -1);
    $sets = array_merge($sets, $data);
}

$new = json_encode($sets, JSON_PRETTY_PRINT);
echo '<pre>';
echo $new;

$fp = fopen('combined_en.json', 'w');
fwrite($fp, $new);
fclose($fp);

2 个答案:

答案 0 :(得分:3)

嗯,一种方法是使用array_filter函数。来自documentation

array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )
     

如果未提供callback,则array等于FALSE的所有条目都将被删除。

现在,如果您查看相同的文档,则可以看到sample recursive implementation

<?php
function array_filter_recursive($input)
{
    foreach ($input as &$value)
    {
        if (is_array($value))
        {
            $value = array_filter_recursive($value);
        }
    }

    return array_filter($input);
}

考虑到这些,我们可以写:

$json = file_get_contents($url);
$data = json_decode($json, true);

$filteredData = array_filter_recursive($data);
$filteredJson = json_encode($filteredData, JSON_PRETTY_PRINT);

答案 1 :(得分:1)

最终工作代码。感谢@Jomoos。

function array_filter_recursive($input)
{
    foreach ($input as &$value)
    {
        if (is_array($value))
        {
            $value = array_filter_recursive($value);
        }
    }

    return array_filter($input);
}

$sets = array();
foreach ($urls as $url)
{
    $json = file_get_contents($url);
    $data = json_decode($json, true);
    foreach ($data as $key => $innerObject) {
        if (isset(
            $innerObject['SPEC_Bullet point 1'],
            $innerObject['SPEC_Bullet point 2'],
            $innerObject['SPEC_Bullet point 3']
        )) {
            unset(
                $data[$key]['SPEC_Bullet point 1'],
                $data[$key]['SPEC_Bullet point 2'],
                $data[$key]['SPEC_Bullet point 3']
            );
        }
    }
    $json = substr($json, 1, -1);
    $sets = array_merge($sets, $data);
    $filteredData = array_filter_recursive($sets);
}


$new = json_encode($filteredData, JSON_PRETTY_PRINT);
echo '<pre>';
echo $new;

$fp = fopen('combined_en.json', 'w');
fwrite($fp, $new);
fclose($fp);