2017-02-08 7 views
0

я пытался до сих порКак удалить повторяющиеся значения и создать единый массив в PHP

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

Я также попытался разобраться в пользовательском пути с помощью петель, но это так грязно.

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 
    ) 

Желаемый результат:

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 
) 
+4

Пожалуйста, поделитесь, что вы пробовали до сих пор! –

+0

, если вы используете 'fetchAll()' меняете его на 'fetchAll (PDO :: FETCH_ASSOC)', и он даст вам всего 1. – MRustamzade

+1

Я думаю, здесь question_id является своеобразным. Если вы измените запрос MYSQL, откуда вы получаете эти данные, и вы получите уникальные данные для ответа с разными ответами. – Naincy

ответ

3
/** 
* 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']; 
    } 
} 
+0

сделано :) надеюсь, что это поможет –

1

Во-первых, мы должны сделать эти 2 строки в один массив, где каждый ключ является суб массив значений каждой строки.

Так это будет выглядеть следующим образом:

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

чем для каждого ключа, мы используем «array_unique», чтобы получить только определенные значения. так он будет выглядеть следующим образом:

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

наконец просто проверить, если каждая клавиша-массив имеет 1 или больше записей осталось. Если у него есть только один, просто замените его на одно значение.

Код:

$aArrayToParse = 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" 
    ) 
); 

$aTempArray = array(); 

// first let's get it all into one array 
foreach($aArrayToParse as $iKey => $aOneDataSet){ 
     foreach($aOneDataSet as $iDataKey => $mDataValue){ 
       if(!isset($aTempArray[$iDataKey])) 
       { 
         $aTempArray[$iDataKey] = array(); 
       } 
       $aTempArray[$iDataKey][] = $mDataValue; 
     } 
} 

// than check and remove all the duplicants 
foreach($aTempArray as $iKey => &$aData){ 
     $aData = array_unique($aData); 
     if(count($aData) == 1) 
     { 
       $aData = $aData[0]; 
     } 
} 
+3

Зачем вам это делать? Что делает эту работу? Можете ли вы * объяснить * свой ответ, пожалуйста. – Martin

+0

Ну, вы объедините их по ключу, чем проверьте, есть ли более одного отдельного значения. если это так, вы просто сделаете его уникальным, иначе у вас будет только одна строка, поэтому вы просто сделаете это значение вместо массива этого значения. –

+0

ok, поэтому отредактируйте свой ответ и добавьте этот полезный самородок информации. к вашему ответу. приветствия ':)' – Martin