dongyipa0028 2014-07-01 06:51
浏览 42
已采纳

从PHP JSON数组中获取唯一值(为什么我必须使用implode?)

Okay, so I'm fairly new to PHP but it's enough like JS so I've been picking it up fairly quickly.

One issue I ran into the other day was getting the values from a JSON file.

My JSON file is 30,000 lines, but here's essentially what it looks like:

{
    "congress": {
        "Brown Sherrod": [{
            "birthday": "1952-11-09"
        }, {
            "gender": "M"
        }, {
            "type": "sen"
        }, {
            "state": "OH"
        }, {
            "party": "Democrat"
        }],
        ...

And anyway, it continues like that for another 29,000 + lines. My code to get the contents of the JSON file is this:

$data = json_decode(file_get_contents('path/to/file/convertcsv.json'), true);

It returns an array like this:

Array (
    [0] => Array (
        [birthday] => 1952-11-09
    )
    [1] => Array (
        [gender] => M
    )
    [2] => Array (
        [type] => sen
    )
    [3] => Array (
        [state] => OH
    )
    [4] => Array (
        [party] => Democrat
    )
)

My issue I ran into is that I can't get the value of, say, ['birthday'] without using implode().

This works: $state = implode($data['congress'][$nameInput][3]);, but this does not: $state = $data['congress'][$nameInput][3];

Is there a reason why? I've read the docs on implode() (join array elements with string) and from what I gather from SO and the PHP docs this is how you get the value, but why? It makes no sense to have to convert the array to a string in order to get the value. In JavaScript to get the value from an array (or even a key-value) you just use the ['key'] or the [index] of the array, and it'll give you the value.

I feel like either I'm goofing on something major (not unlikely) or PHP is just weird -- probably the former. So, to reiterate my question (because I can ramble) am I making this too complex or is PHP just weird (and if so, is there a reason)?

  • 写回答

1条回答 默认 最新

  • doudiandi6967 2014-07-01 06:55
    关注

    Try below :-

    $state = $data['congress'][$nameInput][3]['state']
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探