替换或覆盖PHP中的时间值

时间:2019-11-24 22:24:21

标签: php

我正在尝试替换时间值,如何在php中覆盖或替换

    "users": [
        {
            "1": {
                "time": null
            }
        }
    ]
}';`

1 个答案:

答案 0 :(得分:0)

如果保留该结构,则可以遍历用户数组。

function replaceTimeValueForUserWithId($users, $id) {
    // iterate through your users array
    foreach($users['users'] as &$user) {
        if (isset($user[$id])) {
            $user[$id]['time'] = date("Y-m-d");
        }
    }
    return $users;
}

$json = '
    {
        "users": [
            {
                "1": {
                    "time": null
                }
            },
            {
                "2": {
                    "time": null
                }
            }
        ]
    }
';

// convert the json to a php array
$users = json_decode($json, true);
$users = replaceTimeValueForUserWithId($users, 2);

// re-encode the php array to json
echo json_encode($users);