drvvepadi289421028 2017-02-08 08:19
浏览 34
已采纳

如何在PHP中删除重复值并创建单个数组

I have tried so far

$result = array_map("unserialize", array_unique(array_map("serialize", $surveyData)));

I have also tried to sort out in custom way using loops but it is so much messy.

Array
(
    [0] => Array
    (
        [question_id] => 8
        [answer] => 10 patients
        [question_type] => 1
        [question] => How many diabetes patients do you see per month?
        [question_no] => 3
        [survey_id] => 2
        [name] => Health Pharmacist Digital Advantage
        [description] => Free One Year Subscription to Diabetes Health Pharmacist Digital Advantage magazine
    )

[1] => Array
    (
        [question_id] => 8
        [answer] => 30 patients
        [question_type] => 1
        [question] => How many diabetes patients do you see per month?
        [question_no] => 3
        [survey_id] => 2
        [name] => Health Pharmacist Digital Advantage
        [description] => Free One Year Subscription to Diabetes Health Pharmacist Digital Advantage magazine
    )

Desired result:

Array
(
    [0] => Array
    (
    [question_id] => 8
    [answer] => Array(
        [0] => 10 patients,
        [1] => 30 patients,
    )
    [question_type] => 1
    [question] => How many diabetes patients do you see per month?
    [question_no] => 3
    [survey_id] => 2
    [name] => Health Pharmacist Digital Advantage
    [description] => Free One Year Subscription to Diabetes Health Pharmacist Digital Advantage magazine
)

展开全部

  • 写回答

2条回答 默认 最新

  • donglin1692 2017-02-08 08:29
    关注
    /**
     * empty array for example. This has to be your data.
     */
    $questions = [];
    
    /**
     * The target array, where we will use the question id to prevent duplicate questions.
     */
    $mergedQuestions = [];
    
    foreach($questions as $question) {
        // save the current question id to a variable to make the code more readable.
        $currentQuestionId = $question['question_id'];
    
        // if the array key with the question id of the current question exists in the target array,
        // we can just put the answer to the answer array of the target array with the question id
        // as the array key.
        if(array_key_exists($currentQuestionId, $mergedQuestions) {
            $mergedQuestions[$currentQuestionId]['answer'][] = $question['answer'];
        }else {
            // if we don't find the question id as an array key in the target array,
            // we can be sure its not there yet and just save the question there.
            $mergedQuestions[$currentQuestionId] = $question;
    
            // we want to have the answer field in the question as an array field and thats
            // what we are doing here.
            $mergedQuestions[$currentQuestionId]['answer'] = [$question['answer'];
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?