PHP在数组中的每个元素的末尾添加数组元素

时间:2018-02-01 00:10:57

标签: php pdo

我无法弄清楚如何合并以下示例:

$postsArray = [];


***some query;
$result = $stmt->fetchAll(PDO::FETCH_NUM);  

foreach ($result as $row) {

    $postsArray[] = [
    "externalPostId"=>$row[0],
    "numOfComments"=>$row[1],
    "numOfLikes"=>$row[2]
    ];

    ***another query;
    $topCommentsArray = [];

    $result1 = $stmt->fetchAll(PDO::FETCH_NUM);

    foreach ($result1 as $row) {
       $topCommentsArray[] = [
       "commentId"=>$row[0],
       "externalPostId"=>$row[1],
       "numOfLikes"=>$row[2]
       ];
    };
}

我应该怎样做才能将$ topCommentsArray作为数组元素添加到$ postArray中每个元素的末尾。

注意里面的内容。

示例:

array(2) {
  [0]=>
  array(5) {
    ["externalPostId"]=>
    string(17) "1234567"
    ["numOfComments"]=>
    int(0)
    ["numOfLikes"]=>
    int(0)
    array(5) {
      ["commentId"]=>
      string(7) "1234567"
      ["externalPostId"]=>
      int(10) 1234567
      ["numOfLikes"]=>
      int(0)
    }
  }
  [1]=>
  array(5) {
    ["externalPostId"]=>
    string(17) "1235467"
    ["numOfComments"]=>
    int(0)
    ["numOfLikes"]=>
    int(0)
    array(5) {
      ["commentId"]=>
      string(7) "5634217"
      ["externalPostId"]=>
      int(10) 7654321
      ["numOfLikes"]=>
      int(0)
    }
  }
}

感谢帮助人员。

1 个答案:

答案 0 :(得分:0)

要回答您的问题,我认为归结为:如何将$topCommentsArray放入$postsArray

以下内容可行:

<?php

$result = $stmt->fetchAll(PDO::FETCH_NUM);  

$postsArray = [];

// add a key so you can reference a single array
foreach ($result as $key => $row) {

    // use an array
    $postsArray[$key] = [
        "externalPostId"=>$row[0],
        "numOfComments"=>$row[1],
        "numOfLikes"=>$row[2]
    ];

    // sub query for comments
    $comments = $stmt->fetchAll(PDO::FETCH_NUM);

    $topCommentsArray = [];
    foreach ($comments as $comment) {
       $topCommentsArray[] = [
           "commentId"=>$comment[0],
           "externalPostId"=>$comment[1],
           "numOfLikes"=>$comment[2]
       ];
    };

    // attach your comments to the array
    $postsArray[$key]['topComments'] = $topCommentsArray;
}