如何更改json键值?

时间:2017-02-10 13:12:53

标签: php json

我有以下从sql数据库中提取并编码的json数据。 我想改变一天的值,以便它是实际的一天,即0 =星期一6 =星期日。有没有办法做到这一点。对不起,我是新手编码

post '/save_data' => 'controller_name#action'

2 个答案:

答案 0 :(得分:3)

这就是你要找的东西:

<?php
$json='[{"Day":"0","Hour":"1","Subject":"Computing"},
{"Day":"0","Hour":"3","Subject":"Computing"},
{"Day":"0","Hour":"7","Subject":"Computing"},
{"Day":"1","Hour":"1","Subject":"Physics"},
{"Day":"1","Hour":"5","Subject":"Computing"},
{"Day":"1","Hour":"9","Subject":"Physics"},
{"Day":"1","Hour":"11","Subject":"Physics"},
{"Day":"2","Hour":"1","Subject":"Computing"}]';
$transform=array(
    0=>"Monday",
    1=>"Tuesday",
    2=>"Wednesday",
    3=>"Thursday",
    4=>"Friday",
    5=>"Saturday",
    6=>"Sunday"
);

$json=json_decode($json);
foreach($json as $key) $key->Day=$transform[$key->Day];
echo "<pre><h2>";
echo print_r($json);
?>

输出:

Array
(
    [0] => stdClass Object
        (
            [Day] => Monday
            [Hour] => 1
            [Subject] => Computing
        )

    [1] => stdClass Object
        (
            [Day] => Monday
            [Hour] => 3
            [Subject] => Computing
        )

    [2] => stdClass Object
        (
            [Day] => Monday
            [Hour] => 7
            [Subject] => Computing
        )

    [3] => stdClass Object
        (
            [Day] => Tuesday
            [Hour] => 1
            [Subject] => Physics
        )

    [4] => stdClass Object
        (
            [Day] => Tuesday
            [Hour] => 5
            [Subject] => Computing
        )

    [5] => stdClass Object
        (
            [Day] => Tuesday
            [Hour] => 9
            [Subject] => Physics
        )

    [6] => stdClass Object
        (
            [Day] => Tuesday
            [Hour] => 11
            [Subject] => Physics
        )

    [7] => stdClass Object
        (
            [Day] => Wednesday
            [Hour] => 1
            [Subject] => Computing
        )

)

答案 1 :(得分:2)

无论您使用何种语言,您都需要制作代码以遵循以下伪代码:

您的JSON文本是一个对象数组。让我们调用jsonArray和jsonElement中的每个对象:

for each jsonElement in jsonArray loop
   case (jsonElement.Day)
    when 0: assign jsonElement.Day to "Moday"        
    when 1: assign jsonElement.Day to "Tuesday"
    ...
    when 6: assign jsonElement.Day to "Sunday"
end loop