【问题标题】:Create multiple JSON objects using PHP associative array使用 PHP 关联数组创建多个 JSON 对象
【发布时间】:2016-05-11 10:49:03
【问题描述】:

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

$meta = array();
while($res = mysqli_fetch_assoc($query)) {
    // $meta[] = $res;
    $meta[] = 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

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

这是我目前的回应:

{
"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)"
    }
  ]
}

我理想的架构是

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

【问题讨论】:

  • 试试$meta['player'][] = array(..)
  • 你不必做任何事情!回声 json_encode($meta);在 meta 中,每个对象都是一个玩家。你仍然想要在播放器中再次 $players[] = array('player'=>$meta);然后回显 json_encode($players);会给出想要的结果
  • @SumeetDarade 是的,你明白。它们已经是对象,我只想在数据之前称每个“玩家”。您的建议打印出players [ player->all objects ] 我想要players [player1 : {data1} player2 : {data2} ] 等等!希望这是有道理的。
  • 是的!当我看到 rjhdby 的回答时,实际上得到了它。他的回答应该有效。

标签: php mysql arrays json


【解决方案1】:
$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

如果我理解问题

【讨论】:

    猜你喜欢
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多