sql >> Base de Datos >  >> RDS >> Mysql

¿Cómo reconstruir una matriz sin repeticiones y otros límites?

Esto es lo que finalmente se me ocurrió que funcionó (después de intentar sin éxito crear la consulta que necesitaba para lograr lo mismo)...

La matriz original $theresults contiene las 60 preguntas de las 5 categorías diferentes. Comienzo creando una matriz de todas las categorías de preguntas...

// Create array of all categories
$allcategories = array();
$this->db->select('category_id');
$this->db->where('template_id',$template_id);
$query_thecategories = $this->db->get('categories');
$number_thecategories = $query_thecategories->num_rows();
if ($number_thecategories>0) {
    foreach ($query_thecategories->result() as $row_thecategory) {
        $thecategory = 'cat_' . $row_thecategory->category_id;
        $$thecategory = '0';
        $allcategories[] = $row_thecategory->category_id;
    }
}

Luego utilizo la siguiente función para extraer todas las combinaciones únicas de categorías...

function array_search_by_key($array, $key, $value) {
    if(!is_array($array)) {
        return [];
    }
    $results = [];
    foreach($array as $element) {
        if(isset($element[$key]) && $element[$key] == $value) {
            $results[] = $element;
        }
    }
    return $results;
}

$uniquecombos = uniquecombos($allcategories, 2);

Por último, recorro cada uno de los combos para obtener preguntas que coincidan con cada categoría en el par y almacenar el resultado en una nueva matriz. (Hago un bucle tres veces porque cada emparejamiento de categorías se usará tres veces (10 combinaciones de pares de preguntas x 3 bucles =60 preguntas). También elimino cada pregunta que extraigo del $theresults original. array para asegurar que no haya duplicados...

// Create an empty array to capture the paired questions
$pairs = array();

// Loop through unique combos array 3 times to build pairings
for($combos = 1; $combos <= 3; $combos++) {
    foreach ($uniquecombos as $theset) {
        // Get two categories in pair
        $firstcategory = $theset[0];
        $secondcategory = $theset[1];

        // Gather other arrays which matches each category
        $matchesfirst = array_search_by_key($theresults,'category_id',$firstcategory);
        shuffle($matchesfirst);
        $matchessecond = array_search_by_key($theresults,'category_id',$secondcategory);
        shuffle($matchessecond);

        // Get question from each new array & add; remove selected question from the original array
        $pairs[] = $matchesfirst[0];
        unset($theresults[$matchesfirst[0]['question_id']]);
        $pairs[] = $matchessecond[0];
        unset($theresults[$matchessecond[0]['question_id']]);
    }
}

¡Ojalá esto ayude a alguien más!