1
{
    "available":18,
    "bind":0,
    "info":"",
    "hours_definitions":[
        {
            "value":"21:40"
        },
        {
            "value":"22:50"
        }
    ],
    "hours":{
        "21:40":{
            "available":1,
            "bind":0,
            "info":"",
            "notes":"",
            "price":3000,
            "promo":0,
            "status":"available"
        },
        "22:50":{
            "available":1,
            "bind":0,
            "info":"",
            "notes":"",
            "price":3000,
            "promo":0,
            "status":"available"
        }
    },
    "notes":"",
    "price":2000,
    "promo":0,
    "status":"available"
}

I have JSON array ($dataar), where I need to change "available" to 0 where "hours" array 21:40.

I am trying to use foreach:

$dataar1 = json_decode($dataar, true);
$dataar2 = $dataar1['hours'];
$hour = "21:40";
foreach ($dataar2 as $key => $entry) {
     if ($key == $hour) {
        $dataar2[$key]['available'] = 0;
    }
}

And I get $dataar2[$key]['available'] = 0, but when I am trying to json_encode it back, i see available:1 again.

How can I fix it?

1
  • Add the code you use to encode it back to JSON - I think you might not be encoding the correct variable. Commented Jan 21, 2015 at 23:04

2 Answers 2

4

You aren't changing the actual variable per-say, you're just assigning it to a new variable and changing that. This will work:

$dataar1 = json_decode($dataar, true);

foreach($dataar1['hours'] as $key => &$val) {
    if($key == '21:40') {
        $val['available'] = 0;
    }
}

The above example is using PHP's passing by-reference to modify the original array.

Example

Sign up to request clarification or add additional context in comments.

Comments

1

You are only changing $dataar2, which is a new variable and no relation to the original. Try this instead:

$dataar1 = json_decode($dataar, true);
$hour = "21:40";
foreach ($dataar1['hours'] as $key => $entry) {
     if ($key == $hour) {
        $dataar1['hours'][$key]['available'] = 0;
    }
}
$dataar = json_encode($dataar1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.