根据 id 值将数据行转换为分层的父子结构[重复]

问题描述 投票:0回答:2

我的数组:

Array ( 
  [0] => Array (
    [TYPE] => 'Question',
    [PARTY_ID] => 112,
    [PARENT_USER_CONTENT_ID] => ''
  ) 
  [1] => Array (
    [TYPE] => 'Anwser',
    [PARTY_ID] => 115,
    [PARENT_USER_CONTENT_ID] => 112
  ) 
)

我想要什么:

Array ( 
  [0] => Array ( 
    [TYPE] => 'Question',
    [PARTY_ID] => 112,
    [PARENT_USER_CONTENT_ID] => '',
    [0] => Array (
      [TYPE] => 'Anwser',
      [PARTY_ID] => 115,
      [PARENT_USER_CONTENT_ID] => 112
    ) 
  ) 
)

因此,这个想法是从基本数组开始,将问题作为数组元素及其子元素 anwser,其parent_user_content_Id 等于问题 party_id。

我试过这个:

$new_array = array();
foreach($start_array as $k => $v ){
    if($v['TYPE'] == 'Question'){
        $new_array[] = $v;
    }  
}

通过这种方式,我只会将问题作为新数组的元素,我正在努力解决如何向其添加子元素的问题。

php arrays parent-child hierarchical-data
2个回答
1
投票

这假设每个问题只有一个答案:

$arr = [
    [ 'TYPE' => 'Answer', 'PARTY_ID' => 115, 'PARENT_USER_CONTENT_ID' => 114 ],
    [ 'TYPE' => 'Question', 'PARTY_ID' => 112, 'PARENT_USER_CONTENT_ID' => '' ],
    [ 'TYPE' => 'Question', 'PARTY_ID' => 113, 'PARENT_USER_CONTENT_ID' => '' ],
    [ 'TYPE' => 'Answer', 'PARTY_ID' => 116, 'PARENT_USER_CONTENT_ID' => 113 ],
    [ 'TYPE' => 'Question', 'PARTY_ID' => 114, 'PARENT_USER_CONTENT_ID' => '' ],
    [ 'TYPE' => 'Answer', 'PARTY_ID' => 117, 'PARENT_USER_CONTENT_ID' => 112 ]
];

$indexed = array_combine(array_column($arr, 'PARTY_ID'), $arr);
$answers = array_flip(array_filter(array_column($arr, 'PARENT_USER_CONTENT_ID', 'PARTY_ID')));

foreach ($answers as $parentPartyId => $childPartyId) {
  $result[] = array_merge($indexed[$parentPartyId], [ 'ANSWER' => $indexed[$childPartyId]]);
}

print_r($result);

测试3v4l


0
投票

您可以使用 2 个循环先处理问题,然后再处理答案。

$new_array = array();

// first loop to process the questions
foreach($start_array as $arr){

    // add questions to the $new_array first
    if ($arr['TYPE'] == "Question"){

        $new_array[] = [
            'TYPE' => $arr['TYPE'],
            'PARTY_ID' => $arr['PARTY_ID'],
            'PARENT_USER_CONTENT_ID' => $arr['PARENT_USER_CONTENT_ID',
            'ANSWERS' => []
        ];
    }
}

// second loop to process answers
foreach($start_array as $arr2){

    // add answers to the $new_array by matching the IDs
    if ($arr2['TYPE'] == "Anwser"){

        $parentQuestionId = $arr2['PARENT_USER_CONTENT_ID'];

        // looping through our new question array to find the correct parent question
        foreach($new_array as &$question){

            if ($question['PARTY_ID'] == $parentQuestionId) {

                // adding the answer to the correct parent question
                $question['ANSWERS'][] = $arr2;

            }
        }
    }
}

使用 2 个循环似乎有些夸张,但它可以让您考虑所有答案而不会遗漏任何一个。

© www.soinside.com 2019 - 2024. All rights reserved.