无法更改数组 php 中的值

Can't change value in array php

{
    "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"
}

我有 JSON 数组 ($dataar),我需要将 "available" 更改为 0,其中 "hours" 数组 21:40.

我正在尝试使用 foreach:

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

我得到了 $dataar2[$key]['available'] = 0,但是当我试图 json_encode 它回来时,我又看到了 available:1。

我该如何解决?

您只是更改了$dataar2,这是一个新变量,与原始变量无关。试试这个:

$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);

你并没有改变实际的变量,你只是将它分配给一个新变量并改变它。这将起作用:

$dataar1 = json_decode($dataar, true);

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

上面的例子是用PHP's passing by-reference修改原数组

Example