【问题标题】:How would you convert this JSON request to a new JSON output in PHP?您如何将此 JSON 请求转换为 PHP 中的新 JSON 输出?
【发布时间】:2011-06-23 22:16:49
【问题描述】:

我正在尝试将 JSON 请求转换为新的 JSON 输出,因为我需要重命名一些正在使用的变量才能在日历中工作。 http://arshaw.com/fullcalendar/ 日历附带一个示例 PHP 设置以输出 JSON。

如何让 SAMPLE.PHP 将数据作为循环回显,将我的 JSON 文件中的变量名转换为相同的名称?

SAMPLE.PHP = 用于设置从 Jquery 调用的日历 JSON 的文件

<?php

$year = date('Y');
$month = date('m');

echo json_encode(array(

    array(
        'id' => 111,
        'title' => "Event1",
        'start' => "$year-$month-10",
        'url' => "http://www.eventurl.com/1"
    ),

    array(
        'id' => 222,
        'title' => "Event2",
        'start' => "$year-$month-20",
        'end' => "$year-$month-22",
        'url' => "http://www.eventurl.com/2"
    ),

));

?>

结果:

[
{
    "id": 111,
    "title": "Event1",
    "start": "2011-06-10",
    "url": "http://www.eventurl.com/1"
},
{
    "id": 222,
    "title": "Event2",
    "start": "2011-06-20",
    "end": "2011-06-22",
    "url": "http://eventurl.com/2"
}
]

MYJSON = 我想从我自己的 JSON url 中提取我自己的数据,而不是从示例 PHP 创建中的数据(但保留示例 PHP 结构)。这是我的 JSON 请求的结果,我删除了许多其他行只是为了清理这篇文章(myUrl.json)上的混乱:

{
"events": [
    {
        "event": {

            "id": 1164038671,
            "title": "TestEvent",
            "start_date": "2011-06-24 13:00:00",
            "end_date": "2011-06-24 16:00:00",
            "url": "ttp://www.eventurl.com/1",

        }
    },
    {
        "event": {

            "id": 1163896245,
            "title": "Test",
            "start_date": "2011-07-14 13:00:00",
            "end_date": "2011-07-14 16:00:00",
            "url": "ttp://www.eventurl.com/2",

        }
    }
]
}

作为一个测试,我可以像这样检索值来显示:

<?php 

$string = file_get_contents('myUrl.json');
$json_a=json_decode($string,true);

// array method
foreach($json_a[events] as $p)
{
echo '
ID: '.$p[event][id].' <br/>
TITLE: '.$p[event][title].' <br/>
START DATE: '.$p[event][start_date].' <br/>
END DATE: '.$p[event][end_date].' <br/>
URL: '.$p[event][url].' <br/>

<br/><br/>
';

}
?>

【问题讨论】:

    标签: php html json


    【解决方案1】:

    为什么不直接解码传入的 JSON,将其处理为您想要的,然后对 JSON 进行编码并打印出来?

    如果您需要重命名变量(或键),则设置一个$tmp 变量。 也就是说,

    $json_b['key2'] = $json_a['key1'];
    

    所以,我想你的代码应该是这样的:

    <?php 
    
        $string = file_get_contents('myUrl.json');
        $json_a=json_decode($string,true);
        $json_b = array();
    
        // array method
        foreach($json_a[events] as $p)
        {
            $json_b[event]['ID'] = $json_a[event][id];
            $json_b[event]['TITLE'] = $json_a[event][title];
            //and so on...
        }
    
        echo json_encode($json_b);
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 2018-06-06
      • 1970-01-01
      • 2015-06-01
      • 2019-11-15
      • 1970-01-01
      • 2013-12-13
      相关资源
      最近更新 更多