如何在发生特定值时在另一个数组项旁边添加数组项

时间:2017-04-11 11:30:06

标签: php arrays loops sorting

这里我有一个包含基本注释值的嵌套数组

//cid is comment id and pid is parent id
$comments = array(
              array(
                'cid' = '47',
                'pid' = '0',
                'comment' = 'This is comment'
              ),
              array(
                'cid' = '48',
                'pid' = '0',
                'comment' = 'This is another comment'
              ),
              array(
                'cid' = '49',
                'pid' = '47',
                'comment' = 'This is child comment to parentID 47'
              ),
            );

我想要的最终结果是任何具有parentID的注释数组项应该在与父ID匹配的commentID之后重新定位。为了使其可视化,具有父项的注释数组是对原始注释的回复。到目前为止,我管理了很多

//main loop
foreach ($comments as $index => $val) {

    $cids[] = $val['cid'];

    if($val['pid'] > 0) {
        foreach ($cids as $cidindex => $cid ) {

            if($val['pid'] == $cid) {
                $results[$index] = $val;
                $results[$index + 1] = _comment_load($cid, $array);
            }
        }
    } 
    else {
        $results_ano[$index] = $val;
    }
}//end of main loop

//loads comment
function _comment_load($cid, $array) {
    foreach ($array as $Key => $item) {
        if($item['cid'] == $cid) {
            return $item;
        }
    }
}

所以在合并$results$results_ano之后,我开始print_r

Array
(
    [2] => Array
        (
            [pid] => 47
            [cid] => 49
        )

    [3] => Array
        (
            [pid] => 0
            [cid] => 47
        )

    [0] => Array
        (
            [pid] => 0
            [cid] => 47
        )

     [1] => Array
        (
            [pid] => 0
            [cid] => 48
        )
)

我确实设法得到了我想要的东西,但现在commentId = 47正在重复,我希望从结果数组中删除重复的cid项数组。

1 个答案:

答案 0 :(得分:0)

我设法通过在主循环'

之后进行以下操作来实现这一目标
    foreach ($results as $key => $value) {
      foreach ($results_ano as $anokey => $anovalue) {
        if($anovalue['cid'] == $value['cid']) {
         //Ignore Everything in here
        }else {
            $finalresults[] = $anovalue;
        }
     }
   }

  $merge = $results = $finalresults;

给了我一个没有重复项目的数组。