PHP正在努力删除包含双引号的部分JSON字符串

时间:2014-07-01 13:32:30

标签: php arrays json

尝试将以下内容分解为一系列日期......

[["custom",{"2014":{"7":{"14":true}}}],["custom",{"2014":{"7":{"7":true}}}]]

$availableDatesCodeStripped = substr($availableDatesCode, 1, -2);
// Result - ["custom",{"2014":{"7":{"14":true}}}],["custom",{"2014":{"7":{"7":true}}}

$availableDatesCodeArray = explode("],", $availableDatesCodeStripped);
// Array Element 1 Result - ["custom",{"2014":{"7":{"14":true}}}
// Array Element 2 Result - ["custom",{"2014":{"7":{"7":true}}}

foreach($availableDatesCodeArray as $key => $value) {
    $availableDatesCodeArray[$key] = str_replace(":true}}}", " ", $value);
}

// Array Element 1 Result - ["custom",{"2014":{"7":{"14"
// Array Element 2 Result - ["custom",{"2014":{"7":{"7"

foreach($availableDatesCodeArray as $key=>$value){
    $availableDatesCodeArray[$key] = str_replace("[\"custom\",{\"", "", $value);
}

// Array Element Results - NO CHANGE!

我的目标是最终......

2014-7-14

2014-7-7

因此,如果有人能够更好地解决问题,请说出来。

3 个答案:

答案 0 :(得分:4)

您是否考虑过正确解析输入?

$raw = json_decode($availableDatesCode,true);
$output = array();
foreach($raw as $date) {
    foreach($date[1] as $year => $md) {
        foreach($md as $month => $days) {
            foreach($days as $day => $_) {
                // $_ above because we don't care about the value
                $output[] = sprintf("%04s-%02s-%02s",$year,$month,$day);
            }
        }
    }
}
var_dump($output);

答案 1 :(得分:2)

即使您要解析它,您也希望将其标记化或使用正则表达式。这种字符串替换只会杀死你并完全无法维护。

话虽这么说,你的传入日期格式非常疯狂。看起来它被设计为一种在哈希表中存储多个日期的方法,但设计有点奇怪。

我被叫走了,被殴打了答案 - 但尼尔的代码没有成功。问题在于他正在寻找“定制”。作为键,它实际上是传入数组中的值。以下是针对您的测试数据进行测试的。

$availableDatesCode = '[["custom",{"2014":{"7":{"14":true}}}],["custom",{"2014":{"7":{"7":true}}}]]';
$arr = json_decode($availableDatesCode,true);
$dates = array();
foreach ($arr as $dateItem) {
    if ($dateItem[0] == 'custom') // assuming you only want things marked as custom.
    {
        $pDate = array();
        foreach ($dateItem[1] as $year=>$dateMore)
        {
            foreach ($dateMore as $month=>$dateMore2)
            {
                foreach ($dateMore2 as $day=>$ex)
                {
                    $dates[] = implode('-',array($year, $month, $day));
                }
            }
        }
    }
}

print_r($dates);

答案 2 :(得分:0)

没有json_decode的快速解决方案。

<?php
$json = '[["custom",{"2014":{"7":{"14":true}}}],["custom",{"2014":{"7":{"7":true}}}]]';
preg_match_all("/([0-9]{4})\W{4}([0-9]{1,2})\W{4}([0-9]{1,2})/", $json, $match);

for ($i = 0;$i < count($match[0]); $i++) {
    echo $match[1][$i]."-".$match[2][$i]."-".$match[3][$i];
}