使用PHP关联数组创建多个JSON对象

时间:2016-05-11 10:49:04

标签: php mysql arrays json

我正在尝试创建体育运动员的JSON响应。我有这个脚本查询MySQL数据库并生成一个关联数组。

{
"players": [
    {
        "guid": "1",
        "name": "Matias Aguero",
        "dob": "1981-02-13",
        "birthplace": "San Nicolas, Argentina",
        "height": "1.83m (6' 0\")",
        "weight": "109kg (17st 2lb)",
        "position": "Prop",
        "honours": "40 caps"
    },
    {
        "guid": "2",
        "name": "George Catchpole",
        "dob": "1994-02-22",
        "birthplace": "Norwich, England",
        "height": "1.85em (6ft 1\")",
        "weight": "104kg (16st 5lb)",
        "position": "Centre",
        "honours": ""
    },
    {
        "guid": "3",
        "name": "Logovi'i Mulipola",
        "dob": "1987-03-11",
        "birthplace": "Manono, W Samoa",
        "height": "1.93 (6' 4\")",
        "weight": "130kg (20st 6lb)",
        "position": "Prop",
        "honours": "Samoa (17 caps)"
    }
  ]
}

我希望能够返回一个"播放器"数据库中每个玩家的JSON对象,但我不确定如何创建该结构。

以下是我目前的回复:

"players" : [ "player" { "data" } ] // APOLOGIES FOR THE SHORTHAND

我理想的架构是

@RouteConfig([
  {
    path: 'sweet/:id',
    name: 'SweetDetailLandingPage',
    component: SweetDetailComponent,
    data: { fromLink: false, fromDeepLink: true }
  },
{
    path: 'sweet/:id',
    name: 'SweetDetailFromLink',
    component: SweetDetailComponent,
    data: { fromLink: true, fromDeepLink: false }
  }
])

1 个答案:

答案 0 :(得分:0)

$meta = array();
while($res = mysqli_fetch_assoc($query)) {
    // $meta[] = $res;
    $meta[$res['name']] = array(
        'guid' => $res['guid'],
//        'name' => $res['name'],
        'dob' => $res['date_of_birth'],
        'birthplace' => $res['birthplace'],
        'height' => $res['height'],
        'weight' => $res['weight'],
        'position' => $res['position'],
        'honours' => $res['honours']
    );
}

$meta = json_encode(array('players' => $meta), JSON_PRETTY_PRINT);
echo $meta

如果我不理解问题