无法在数组php中更改值

时间:2015-01-21 22:51:23

标签: php arrays json foreach

{
    "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 ),我需要将“可用”更改为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回来时,我又看到了:1。

我该如何解决?

2 个答案:

答案 0 :(得分:3)

你不会改变每个实际变量,你只是将它分配给一个新变量并改变它。这将有效:

$dataar1 = json_decode($dataar, true);

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

以上示例使用PHP's passing by-reference修改原始数组。

Example

答案 1 :(得分: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);