php - 如何通过 PHP 对齐其帖子下的评论
问题描述
我有两个 json 记录,我可以成功地分别显示它的记录。
这是我的问题。我想根据第一条记录的 postid 附加并显示第二条记录的评论。
也就是说,我想根据 postid 将所有评论放在它的帖子下。
<?php
// first record
$output ='
{"results":[
{"postid":101, "post":"my first post"},
{"postid":102, "post":"my second post"},
{"postid":103, "post":"my third post"}]
}
';
// second record
$output2 ='
{"results":[
{"postid":101,"comment":"my first comment"},
{"postid":102, "comment":"my second comment"},
{"postid":103,"comment":"my third comment"}
]
}
';
$json = json_decode($output, true);
foreach($json["results"] as $res){
echo $id = $res['postid'];
echo "<br><br>";
echo $post = $res['post'];
echo "<br><br>";
}
$json2 = json_decode($output2, true);
foreach($json2["results"] as $res1){
echo $id = $res1['postid'];
echo "<br><br>";
echo $comment = $res1['comment'];
echo "<br><br>";
}
?>
解决方案
循环遍历两个数组,找到匹配postids
项,如果匹配,则将post
第一个数组的第一个数组添加到第二个数组,在该键处。
https://paiza.io/projects/-5zgfBWUs3jOJdNm0e1FZg
<?php
$output='{"results":[{"postid":101, "post":"my first post"},{"postid":102, "post":"my second post"},{"postid":103, "post":"my third post"}]}';
$output2='{"results":[{"postid":101,"comment":"my first comment"},{"postid":102, "comment":"my second comment"},{"postid":103,"comment":"my third comment"}]}';
$output = json_decode($output, true);
$output2 = json_decode($output2, true);
foreach($output["results"] as $val1){
foreach($output2["results"] as $key2 => $val2){
if($val1["postid"] == $val2["postid"]){
$output2["results"][$key2]["post"] = $val1["post"];
}
}
}
print_r($output2);
输出:
Array
(
[results] => Array
(
[0] => Array
(
[postid] => 101
[comment] => my first comment
[post] => my first post
)
[1] => Array
(
[postid] => 102
[comment] => my second comment
[post] => my second post
)
[2] => Array
(
[postid] => 103
[comment] => my third comment
[post] => my third post
)
)
)
推荐阅读
- javascript - 如何删除输入值?
- docker - Nginx+uwsgi。在本地主机上工作正常,但在远程机器上不行。为什么
- javascript - ios设备上带有视频空白的iframe
- amazon-quicksight - AWS QuickSight 与 IoT Analytics 数据存储 - 未导入一列
- python - 隔离图像中的多个暗区
- java - 为什么在 java 命令行中 ^ 之后传递的参数被忽略?
- node.js - Orocommerce 作曲家安装失败
- tcl - 为什么我不能在模块设计中添加时钟向导?
- asp.net-core-webapi - ASP.NET Core Web API 失败,“无法找到此本地主机页面”,json 结果大 - DisableRequestSize 无效
- r - 使用 Rmpfr 在 R 中进行高精度计算