PHP将对象转换为数组的数组
我有3个表,在连接名称并输出角色后PHP将对象转换为数组的数组,php,mysql,mysqli,Php,Mysql,Mysqli,我有3个表,在连接名称并输出角色后 $encoded = array(); while($res = mysqli_fetch_assoc($result)) { echo json_encode($res); } 我知道了 {"student_id":"1","student_name":"john","score_id":"1","score_type":"E","score_name":"England"} {"student_id":"1","student_name":"jo
$encoded = array();
while($res = mysqli_fetch_assoc($result)) {
echo json_encode($res);
}
我知道了
{"student_id":"1","student_name":"john","score_id":"1","score_type":"E","score_name":"England"}
{"student_id":"1","student_name":"john","score_id":"2","score_type":"B","score_name":"Brazil"}
现在我正努力将它们转换成我想要的格式,客户端站点必须有这样的格式
//json
[{
"student_id":"1",
"student_name":"john",
"scores": [{
"score_id":"1",
"score_type":"E",
"score_name":"England"
},{
"score_id":"2",
"score_type":"B",
"score_name":"Brazil"
}]
}]
挑战在于它与同一个人有重复的行。使用数组
$encoded
处理输出,一旦生成,就可以使用JSON打印它
在此解决方案中,数组将按学生id
索引,分数按分数id
索引。对于学生,这是必须的,对于分数,建议:
$encoded = array();
while($res = mysqli_fetch_assoc($result)) {
// Student's details
$encoded[$res['student_id']] = array(
'student_id' => $res['student_id'],
'student_name' => $res['student_name'],
);
// Student's score details
$encoded[$res['student_id']]['scores'][$res['score_id']] = array(
'score_id' => $res['score_id'],
'score_type' => $res['score_type'],
'score_name' => $res['score_name'],
);
}
echo json_encode($encoded);
注意:这是一般性的回答,因为我不知道$res中数据的确切结构。请查找下面的代码以获得问题中提到的json格式
$students = [];
$sampleData = [
[
"student_id"=>"1",
"student_name"=>"john",
"score_id"=>"1",
"score_type"=>"E",
"score_name"=>"England",
],
[
"student_id"=>"1",
"student_name"=>"john",
"score_id"=>"2",
"score_type"=>"B",
"score_name"=>"Brazil",
],
];
foreach ($sampleData as $res) {
//if student not found by id then continue
if (empty($res['student_id'])) {
continue;
}
$student = [];
//get the already exists student to add scores
if(!empty($students[$res['student_id']])) {
$student = $students[$res['student_id']];
}
//prepare the student array
$student['student_id'] = $res['student_id'];
$student['student_name'] = $res['student_name'];
$student['scores'][]['score_id'] = $res['score_id'];
$student['scores'][]['score_type'] = $res['score_type'];
$student['scores'][]['score_name'] = $res['score_name'];
$students[$res['student_id']] = $student;
}
echo json_encode(array_values($students));
希望这有帮助
您可以发现工作示例听起来像是您应该调整查询以删除已编码或解码的json的重复。可以是object或assoc。你知道Doctrine2 ORM吗?使用子属性定义模型(对象)并将其映射到数据库表。条令获取行并构建对象。。。在您的例子中,可能是一个带有分数子对象的学生模型。在某些情况下,由于性能原因,您不使用ORM。。。但是它使处理复杂的数据结构变得更加容易。可以避免这一行吗<代码>$arr=$students[$res['contact_id']]??[];代码>我还没有使用php 7。您的答案不起作用,我尝试了,我给了我2个数组。很抱歉,出现意外错误,请稍后再试或与JDoodle支持部门联系。@globin虽然我已更新了代码,以反映您发布的更新。