V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
kennedy32
V2EX  ›  PHP

初学者提问0916

  •  
  •   kennedy32 · Sep 15, 2013 · 3041 views
    This topic created in 4607 days ago, the information mentioned may be changed or developed.
    如果一个api的返回值是这样的:

    //以下是内容

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

    //以上是内容

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

    无论file还是file_get_contents都要经过explode,我总觉得应该有更简单的一步方法,求指教
    5 replies    1970-01-01 08:00:00 +08:00
    solf
        1
    solf  
       Sep 15, 2013   ❤️ 1
    json_decode?
    kennedy32
        2
    kennedy32  
    OP
       Sep 15, 2013
    @solf tks
    kevinroot
        3
    kevinroot  
       Sep 15, 2013   ❤️ 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
       Sep 15, 2013
    @kevinroot 对object不太熟,还是喜欢加个true进去变成数列
    jybox
        5
    jybox  
       Sep 15, 2013
    <?php

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

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


    http://3v4l.org/bCC5i
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3729 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 10:42 · PVG 18:42 · LAX 03:42 · JFK 06:42
    ♥ Do have faith in what you're doing.