2

我有下表:

-> +-----+---------+-----+-------+--------------+
-> | id1 | fname   | id2 | fname | relationship |
-> +-----+---------+-----+-------+--------------+
-> |   4 | Albaraa |   5 | Sadi  | Father       |
-> +-----+---------+-----+-------+--------------+

我将以下内容分配给变量 $relations:

$relations = $stmt->fetchAll(PDO::FETCH_ASSOC);

最后我用这个打印出这个变量的 JSON 编码:

echo json_encode($relations);

...我得到以下输出:

[{"id1":"4","fname":"Sadi","id2":"5","relationship":"Father"}]

所以这里有几个关于我得到的输出的问题:

1)您可以看到我的输出看起来不正确,因为它应该是这样的:

[{"id1":"4","fname":"Albaraa","id2":"5","fname":"Sadi","relationship":"Father"}]

为什么它不能正确打印,这与表有两列同名“fname”有关吗?如果有任何关于如何解决这个问题的意见,那就太棒了!

2)我很想知道的另一件事是,我实际上想将 JSON 更改为如下所示的位置:

[{"id":"4","name":"Albaraa","id":"5","name":"Sadi","relationship":"Father"}]

有没有一种简单的方法可以将“id1”和“id2”更改为“id”并将“fname”更改为“name”?

再次对此的任何输入将不胜感激!

4

1 回答 1

5

1)fname被覆盖。尝试在 SQL 查询中使用不同的别名来匹配字段。

2)您不应该传递精确的名称匹配属性。它们可能被 JSON 解码器覆盖。最好将它们作为不同的 JSON 部分传递。

[{"id":"4","name":"Albaraa","id":"5","name":"Sadi","relationship":"Father"}]

应该是这样的:

{
    "person1":{"id":4,"name":"Albaraa"},
    "person2":{"id":5,"name":"Sadi"},
    "relationship":"Father"
}

UPDv1:

结果:

-> +-----+---------+-----+--------+--------------+
-> | id1 | fname1  | id2 | fname2 | relationship |
-> +-----+---------+-----+--------+--------------+
-> |   4 | Albaraa |   5 | Sadi   | Father       |
-> +-----+---------+-----+--------+--------------+

尝试像这样转换:

<?php
// $row is sql fetched row.

$person1  = array('id' => $row['id1'], 'name' => $row['fname1']);
$person2  = array('id' => $row['id2'], 'name' => $row['fname2']);
$response = array(
     'person1' => $person1,
     'person2' => $person2,
     'relationship' => $row['relationship']
);

echo json_encode($response);

?>
于 2013-04-30T05:03:10.650 回答