首页 > 解决方案 > 如何通过 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>";

  
}


?>

标签: php

解决方案


循环遍历两个数组,找到匹配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
                )
        )
)

推荐阅读