Domanda

Ho due array che dovrebbero essere uguali.

Quando il var dumping e si afferma se quelli sono uguali, ottengo il seguente output

array(2) {
  [0]=>
  array(3) {
    ["100"]=>         //notice that the key is NOT numeric
    int(0)
    ["strKey1"]=>
    int(0)
    ["strKey2"]=>
    int(0)
  }
  [1]=>
  array(3) {
    ["100"]=>         //notice that the key is NOT numeric
    int(0)
    ["strKey1"]=>
    int(0)
    ["strKey2"]=>
    int(0)
  }
}
There was 1 failure:

1) Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
-    '100' => 0
     'strKey1' => 0
     'strKey2' => 0
+    '100' => 0
 )

Un semplice ciclo foreach per entrambe le matrici che mappano le chiavi per essere di nuovo numeriche, funziona bene, ma non è il più bello hack all'interno di un test.

    $actualArray = array();

    foreach ($actualOriginal as $key => $value) {
        $actualArray[$key] = $value;    
    }

    $expectedArray = array();

    foreach ($expectedOriginal as $key => $value) {
        $expectedArray[$key] = $value;    
    }

Qualche suggerimento per cui questi array non sono considerati uguali?

Grazie per qualsiasi aiuto!

È stato utile?

Soluzione

Conosco solo un modo come ottenere tasti di stringa numerica: convertendo l'oggetto in array

$object = new stdClass();
$object->{'100'} = 0;
$object->strKey1 = 0;
$object->strKey2 = 0;
$array1 = (array) $object;
var_dump($array1);
//array(3) {
//  '100' => -- string
//  int(0)
//  'strKey1' =>
//  int(0)
//  'strKey2' =>
//  int(0)
//}

Quindi, $ Array1 non è uguale a questo $ Array2

$array2 = array('100' => 0, 'strKey1' => 0, 'strKey2' => 0,);
var_dump($array2);
//array(3) {
//  [100] => -- integer
//  int(0)
//  'strKey1' =>
//  int(0)
//  'strKey2' =>
//  int(0)
//}
var_dump($array1 == $array2);
//bool(false)

Non è un bug: https://bugs.php.net/bug.php?id=61655


Anche PhpUnit ha le sue regole di confronto.

$this->assertEquals($array1, $array1); // Fail
$this->assertEquals($array1, $array1); // Pass

https://github.com/sebastianbergmann/phpunit/blob/3.7/phpunit/framework/comparator/array.php

Breve descrizione del confronto PhPUNIT:

$expected = $array1;
$actual = $array1;

$remaining = $actual;
$equal = TRUE;
foreach ($expected as $key => $value){
    unset($remaining[$key]);} // string numeric keys would not be unsetted.

if ($remaining)
    $equal = FALSE;

var_dump($equal);
//bool(false)

Quindi ... lo stai facendo bene. Per ottenere un array "normale" devi ricreare l'array. Potresti usare fooch. Ma Shoter Way è nell'uso delle funzioni di serializzazione.

$this->assertEquals(unserialize(serialize($array1)), unserialize(serialize($array1)));
//Pass

Ma non sembra molto meglio. :^)

Inoltre potresti usare assertSame.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top