@fretburner - your solution returns a lot more than just the required days closed.
array(6) { ["sunday"]=> array(2) { ["open"]=> NULL ["close"]=> NULL } ["id"]=> array(1) { ["id"]=> int(8) } ["monday"]=> array(2) { ["open"]=> NULL ["close"]=> NULL } ["tuesday"]=> array(2) { ["open"]=> NULL ["close"]=> NULL } ["friday"]=> array(2) { ["open"]=> NULL ["close"]=> NULL } ["saturday"]=> array(2) { ["open"]=> NULL ["close"]=> NULL } }
I am also getting a NOTICE that “open” isn’t a proper index for the array, which I am getting in designtrooper’s solution too and to be honest, I am not sure why myself.
@designtrooper - are you looking for a key->value pair with the week days and whether the store is open or closed? If yes, then don’t use array_push, just use the $cl_days[$key] = "closed"
and continue adding to the array outside of the if statement with $cl_days[$key] = "open"
.
I came up with this.
$newTimes = array();
$json = '{"sunday":{"open":null,"close":null},"id":{"id":8},"monday":{"open":null,"close":null},"tuesday":{"open":null,"close":null},"wednesday":{"open":"08:30:00","close":"14:30:00"},"thursday":{"open":"11:00:00","close":"17:00:00"},"friday":{"open":null,"close":null},"saturday":{"open":null,"close":null}}';
$dataArray = json_decode($json, true);
foreach ($dataArray as $day => $times) {
foreach ($times as $time) {
if ( $time === null ) {
$newTimes[$day] = "closed";
} elseif (is_string($time)) {
$newTimes[$day] = "open";
}
}
}
I had to add the “is_string” because of the “id” being in the middle of the JSON, otherwise it could have been just an “else”. Why is the “id” in the middle of the JSON?
This is what I ended up with.
array(7) { ["sunday"]=> string(6) "closed" ["monday"]=> string(6) "closed" ["tuesday"]=> string(6) "closed" ["wednesday"]=> string(4) "open" ["thursday"]=> string(4) "open" ["friday"]=> string(6) "closed" ["saturday"]=> string(6) "closed" }
Scott