He ordenado 2D de la siguiente manera:

$arrRes = array(  
                array("2018-08-01"=>"X" , "2018-08-02"=>"O" , "2018-08-03"=>"O" , "2018-08-04"=>"O"),
                array("2018-08-01"=>"X" , "2018-08-02"=>"X" , "2018-08-03"=>"O" , "2018-08-04"=>"O"),
                array("2018-08-01"=>"X" , "2018-08-02"=>"X" , "2018-08-03"=>"O" , "2018-08-04"=>"X"),
                array("2018-08-01"=>"X" , "2018-08-02"=>"O" , "2018-08-03"=>"O" , "2018-08-04"=>"O"),
           );  

¿Cómo contar "X" y "O" en el conjunto de filas y columnas? quiero el resultado:

// NÚMERO FILA "X":

Array
(
[0] => 1
[1] => 2
[2] => 2
[3] => 1
)

// NÚMERO FILA "O":

Array
(
[0] => 3
[1] => 2
[2] => 2
[3] => 3
)

// NÚMERO COLUMNA "X"

Array
(
[0] => 4
[1] => 2
[2] => 0
[3] => 1
)

// NÚMERO COLUMNA "O"

Array
(
[0] => 0
[1] => 2
[2] => 4
[3] => 3
)

Lo he intentado pero estoy confundida:

foreach($arrRes as $keyRow => $row){
       foreach($row as $keyCol => $col){
            if($col == 'X'){
            ????     
             }elseif($col == 'O'){
            ????     
             }
      } 
    } 
0
maitimo 9 sep. 2018 a las 19:37

3 respuestas

La mejor respuesta

Usando la respuesta splash58 como punto de partida, he agregado varias partes para que sea completa.

Yo uso array_merge(['X' => 0, 'O' => 0], array_count_values($row));, que siempre asegurará que existan entradas 'X' y 'O', esto se muestra más en las columnas que en las filas.

Para las columnas, uso array_column() para extraer cada columna y procesarla de la misma manera que las filas.

$arrRes = array(
    array("2018-08-01"=>"X" , "2018-08-02"=>"O" , "2018-08-03"=>"O" , "2018-08-04"=>"O"),
    array("2018-08-01"=>"X" , "2018-08-02"=>"X" , "2018-08-03"=>"O" , "2018-08-04"=>"O"),
    array("2018-08-01"=>"X" , "2018-08-02"=>"X" , "2018-08-03"=>"O" , "2018-08-04"=>"X"),
    array("2018-08-01"=>"X" , "2018-08-02"=>"O" , "2018-08-03"=>"O" , "2018-08-04"=>"O"),
);  
$row =[];
$col = [];
foreach($arrRes as $row){
    $res[] = array_merge(['X' => 0, 'O' => 0], array_count_values($row));
}
$rowX = array_column($res,"X");
$rowO = array_column($res,"O");
foreach($arrRes[0] as $key => $row){
    $col[] = array_merge(['X' => 0, 'O' => 0], 
            array_count_values(array_column($arrRes,$key)));
}
$colX = array_column($col,"X");
$colO = array_column($col,"O");

print_r($rowX);
print_r($rowO);
print_r($colX);
print_r($colO);

Esto da como salida ...

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 1
)
Array
(
    [0] => 3
    [1] => 2
    [2] => 1
    [3] => 3
)
Array
(
    [0] => 4
    [1] => 2
    [2] => 0
    [3] => 1
)
Array
(
    [0] => 0
    [1] => 2
    [2] => 4
    [3] => 3
)
1
Nigel Ren 9 sep. 2018 a las 17:24

Si conoce sus valores (X / O), puede crear previamente su matriz de resultados. Luego recorra su matriz existente y aumente el recuento row / col según el valor y la posición de la fila / columna. Use array_search ( .. array_keys () ) para obtener el índice de clave de la clave asociativa.

$arraySum = [
             'rows' => ['X'=>[0,0,0,0],'O'=>[0,0,0,0]],
             'cols' => ['X'=>[0,0,0,0],'O'=>[0,0,0,0]]
            ];

foreach($arrRes as $keyRow => $row){
   foreach($row as $keyCol => $col){
      $arraySum['rows'][$col][$keyRow]++;
      $arraySum['cols'][$col][array_search($keyCol,array_keys($row))]++; 
  } 
}

Demo - https://3v4l.org/ROTMP

0
Sean 9 sep. 2018 a las 17:02

Fragmento resuelto / desenredado para ayudarlo a lograr su salida

$printers = array(
    array("2018-08-01" => "X", "2018-08-02" => "O", "2018-08-03" => "O", "2018-08-04" => "O"),
    array("2018-08-01" => "X", "2018-08-02" => "X", "2018-08-03" => "O", "2018-08-04" => "O"),
    array("2018-08-01" => "X", "2018-08-02" => "X", "2018-08-03" => "O", "2018-08-04" => "X"),
    array("2018-08-01" => "X", "2018-08-02" => "O", "2018-08-03" => "O", "2018-08-04" => "O"),
);
//PrinterFilter class to filter our iterator and ONLY return values that start with Printer_
class PrinterFilter extends FilterIterator
{
    public function accept()
    {
        //Only accept values that start with Printer_
        if (false !== strpos(parent::current(), 'X') || false !== strpos(parent::current(), 'O')) {
            return true;
        }
        return false;
    }
}
//Create a new Iterator for the array
//Create a RecursiveArrayIterator around our array
//Create a RecursiveIteratorIterator around that so we can easily navigate it
//Create a PrintFilter interator around that so we can filter
$iterator = new PrinterFilter(new RecursiveIteratorIterator(new RecursiveArrayIterator($printers)));
$counts   = array();
$i        = 0;
$j        = 0;
//Simply iterate over the iterator add new keys as necessary
//Increment existing keys.
foreach ($iterator as $key => $value) {
    $result['rows'][$value][$i] = (isset($counts[$value]) ? ++$counts[$value] : ($counts[$value] = 1));
    $result['cols'][$value][$j] = (isset($result['cols'][$value][$j]) ? ++$result['cols'][$value][$j] : 1);
    $j++;
    if ($j % 4 == 0) {
        $i++;
        $j      = 0;
        $counts = [];
    }
}
foreach ($result['cols'] as $key => $value) {
    $newKeys = array_fill_keys(range(0, 3), 0);
    $result['cols'][$key] += $newKeys;
    ksort($result['cols'][$key]);
}
pr($result);

Aquí está funcionando el código.

1
Rahul 10 sep. 2018 a las 11:27