V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
kennedy32
V2EX  ›  PHP

初学者提问0916

  •  
  •   kennedy32 · 2013-09-15 21:10:21 +08:00 · 2565 次点击
    这是一个创建于 3874 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如果一个api的返回值是这样的:

    //以下是内容

    {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4",
    }

    //以上是内容

    如何最简单方法取得第一个value1

    无论file还是file_get_contents都要经过explode,我总觉得应该有更简单的一步方法,求指教
    5 条回复    1970-01-01 08:00:00 +08:00
    solf
        1
    solf  
       2013-09-15 21:20:28 +08:00   ❤️ 1
    json_decode?
    kennedy32
        2
    kennedy32  
    OP
       2013-09-15 21:29:02 +08:00
    @solf tks
    kevinroot
        3
    kevinroot  
       2013-09-15 21:33:21 +08:00   ❤️ 1
    这种接口一般是给js用的吧,如果js的话用jquery请求的dataType直接写json他会自动给你decode
    $.ajax({
    url : api,
    type : 'post',
    dataType : 'json',
    success : function (data) {
    console.log(data['key1']);
    }
    });

    如果这是要php来请求获取结果之后就用$result = json_decode($data, true);这样会得到一个数组,要获得第一个值的话$result = current($result);如果键名是确定的话就直接$result = $result['key1'];如果是写json_decode($data);他会给你一个stdClass的类,你可以这样获得结果$data->key1
    kennedy32
        4
    kennedy32  
    OP
       2013-09-15 21:46:45 +08:00
    @kevinroot 对object不太熟,还是喜欢加个true进去变成数列
    jybox
        5
    jybox  
       2013-09-15 21:46:59 +08:00
    <?php

    $input = <<< JSON
    {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4"
    }
    JSON;

    echo array_values(json_decode($input, true))[0];


    http://3v4l.org/bCC5i
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5578 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 06:03 · PVG 14:03 · LAX 23:03 · JFK 02:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.