使用php

时间:2019-02-16 10:29:37

标签: php json firebase nosql

我有一个php函数,该函数从firebase数据库获取以下 json 文件,并创建一个名为$data的对象。 请记住,我事先不知道父字段:-LYd55ZsqtoktfA58X91

{
    "-LYd55ZsqtoktfA58X91": {
        "city": "NY",
        "department": "abc0",
        "email": "awesomemail@test.com",
        "fullName": "David Awesome",
        "gender": 1,
        "hireDate": "2019-02-04",
        "isPermanent": false,
        "mobile": "123456789"
    }
}

问题

  

我需要删除第一个父字段,以便输出预期   是:

 {
        "city": "NY",
        "department": "abc0",
        "email": "awesomemail@test.com",
        "fullName": "David Awesome",
        "gender": 1,
        "hireDate": "2019-02-04",
        "isPermanent": false,
        "mobile": "123456789"
   }

我的第一种方法

知道父键。我可以获得-例如-一些属性,然后手动格式化此json。在此示例中,我得到城市价值(NY)。

echo ("City: " . $data["-LYd55ZsqtoktfA58X91"]["city"]);

我的第二种方法

遍历数据,但这可能是“昂贵的”功能。

foreach ($data as $emp ) {
    echo implode($emp, ",");
}

2 个答案:

答案 0 :(得分:2)

给出指定的json数据字符串

$str='{
    "-LYd55ZsqtoktfA58X91": {
        "city": "NY",
        "department": "abc0",
        "email": "awesomemail@test.com",
        "fullName": "David Awesome",
        "gender": 1,
        "hireDate": "2019-02-04",
        "isPermanent": false,
        "mobile": "123456789"
    }
}';
/* decode as an array */
$json=json_decode( $str,true );
/* get the array jeys - specifically the first one */
$key=array_keys( $json )[0];
$data=json_encode( $json[ $key ] );

/* work with results */
printf("<pre>%s\n%s</pre>",$key,print_r($data,true));

输出:

-LYd55ZsqtoktfA58X91
{"city":"NY","department":"abc0","email":"awesomemail@test.com","fullName":"David Awesome","gender":1,"hireDate":"2019-02-04","isPermanent":false,"mobile":"123456789"}

另一种更简洁的方法如下:

$json=json_decode( $str );
$key=array_keys( get_object_vars( $json ) )[0];

echo $json->$key->city; //NY etc

我认为第二种方法优于第一种方法

答案 1 :(得分:0)

鉴于您提供的JSON(带有一个元素的JSON),我建议使用current()

object_id

https://3v4l.org/WQllZ

给出一个包含多个元素的JSON,如果您只想获取城市代码,则可以使用array_column()

<?php

$json = <<<JSON
{
    "-LYd55ZsqtoktfA58X91": {
        "city": "NY",
        "department": "abc0",
        "email": "awesomemail@test.com",
        "fullName": "David Awesome",
        "gender": 1,
        "hireDate": "2019-02-04",
        "isPermanent": false,
        "mobile": "123456789"
    }
}
JSON;

$data = current(json_decode($json, true));

print_r($data);
echo $data['city'];

https://3v4l.org/nkaZF