Reputation: 169
Trying to break down the following into an array of dates...
[["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!
My aim is to end up with...
2014-7-14
2014-7-7
So if anyone has a better solution to the way I'm going about it, please say.
Upvotes: 0
Views: 264
Reputation: 324750
Have you considered parsing your input correctly?
$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);
Upvotes: 4
Reputation: 13173
Fast solution without 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];
}
Upvotes: 0
Reputation: 13435
Even if you were to parse it, you would want to tokenize it or use a regex. This kind of string replacement will just kill you and be wholly unmaintainable.
That being said, your incoming date format is pretty crazy. It looks like it was designed as a way to store multiple dates in a hash table, but the design is sort of odd.
I got called away, and got beaten to the answer -- but Neil's code won't work. The issue there is that he's looking at 'custom' as a key, where it is actually a value in the incoming array. The below is tested against your test data.
$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);
Upvotes: 2