2015-08-17 17 views
5

Ho due oggetti JSON e vorrei confrontare la loro struttura confrontare la loro struttura. Come posso farlo?PHP - confronta la struttura di due oggetti JSON

Questi oggetti vengono generati al volo e a seconda del contenuto dinamico. Ciò significa che gli oggetti sono sempre diversi ma la maggior parte del tempo è la stessa struttura. Voglio essere in grado di prendere le modifiche una volta che si verificano.

Esempio: Questi due oggetti deve essere considerata uguale , perché entrambi hanno la stessa struttura : var index e tag matrice.

{ 
    "index": 0, 
    "tags": [ 
     "abc" 
    ] 
} 
{ 
    "index": 1, 
    "tags": [ 
     "xyz" 
    ] 
} 

Pensieri?

+0

così si vuole verificare se oggetto 1 ha gli stessi campi dell'oggetto 2? – treegarden

+0

Sì, esattamente. Ho provato a utilizzare RecursiveArrayIterator :: hasChildren() per eseguire un'iterazione solo sulle foglie, ma questa soluzione non mi sembra elegante. Qualcuno potrebbe sapere un modo migliore? – Boarking

+0

@Boarking, hai funzionato? – vonUbisch

risposta

1

È un po 'approssimativo, ma si ottiene l'immagine;

$json = '[ 
     { 
      "index": 0, 
      "tags": [ 
       "abc" 
      ] 
     }, 
     { 
      "index": 1, 
      "tags": [ 
       "xyz" 
      ] 
     }, 
     { 
      "foo": 2, 
      "bar": [ 
       "xyz" 
      ] 
     }]'; 

$array = json_decode($json, true); 
$default = array_keys($array[0]); 

$error = false; 
$errors = array(); 
foreach ($array as $index => $result): 
    foreach ($default as $search): 
     if (!isset($result[$search])): 
      $error = true; 
      $errors[] = "Property '{$search}' at entry '{$index}' not found. "; 
     endif; 
    endforeach; 
endforeach; 

if ($error): 
    echo 'Objects are not the same. '; 
    foreach ($errors as $message): 
     echo $message; 
    endforeach; 
endif; 

rendimenti:

Gli oggetti non sono la stessa cosa. "Indice" di proprietà alla voce "2" non trovato. 'Tag' di proprietà nella voce '2' non trovati.

+0

Il problema qui è con l'array predefinito. Come posso generarlo? Tutto quello che ho sono due oggetti JSON. array_keys() non è una buona opzione perché non è ricorsivo. I miei oggetti reali sono molto grandi e hanno molti livelli di nidificazione. Devo essere in grado di confrontare tutto. – Boarking

+0

Non è possibile aspettarsi una certa struttura? Per quanto ne so, per farlo in modo efficiente dovrai aspettarti qualcosa. – vonUbisch

+0

Non ho idea di cosa mi aspetto. Tutto quello che so è che ho due oggetti JSON che probabilmente sono gli stessi ma devo essere sicuro prima di procedere. – Boarking

-1

È possibile convertire la stringa JSON per un array PHP quindi utilizzare il array_diff ($ arr1, $ arr2) funzione per confrontare l'array appena creato con un altro array il risultato è un array che contiene gli elementi del prima matrice che non esiste dell'altra schiera

esempio:

<?php 
    $array1 = '{"name":"myname","age":"40"}'; 
    //convert the obtained stdclass object to an array 
    $array1 = (array) json_decode($array1); 



    $array2 = array("name"=>"myname123","age"=>10); 

    print_r($array2); 

    $result_array = array_diff($array1,$array2); 


    if(empty($result_array[0])){  
     echo "they have the same structure "; 
    } 



?> 
0

si intende per struttura, come matrice modello come:

array ('index' => int, 'tags' => array()) 

Se questo è ciò che si sta cercando di ottenere, provare questo ...

$arr1 = array (
    array (
     'index' => 0, 
     'tags' => ['abc'] 
    ), 
    array (
     'index' => 1, 
     'tags' => ['xyz'] 
    ), 
    array (
     'index' => 2, 
     'tags' => ['xyz'], 
     'boom' => 'granade' 
    ), 
    array (
     'index' => 3, 
     'tags' => 'xyz' 
    ) 
); 

$holder = array(); 

$model = array ('index' => 0, 'tags' => array()); 

for ($i = 0;$i < count($arr1); $i++) 
{ 
    $holder = array_diff(array_merge_recursive($arr1[$i], $model), $model); 

    if (!empty($holder)) 
    { 
     echo "different structure<br>"; 
    } 
    else 
    { 
     echo "same structure<br>"; 

     // for further validation 
     /* 
     $keys = array_keys($model); 

     if (is_int($arr1[$i][$keys[0]]) && is_array($arr1[$i][$keys[1]])) 
      echo "same structure<br>"; 
     else 
      echo "different structure<br>"; 
     */ 
    } 

} 

Esempio di output:

same structure 
same structure 
different structure 
different structure 
7

## È possibile utilizzare questa libreria TreeWalker php.##

TreeWalker è un'API semplice e smal php
(I sviluppato questa biblioteca, spero che ti aiuta)

Offre due metodi
1- Prendi differenza JSON
2- Modifica JSON value (ricorsivamente)

questo metodo restituirà il diference tra il json1 e json2

$struct1 = array("casa"=>1, "b"=>"5", "cafeina"=>array("ss"=>"ddd"), "oi"=>5); 
$struct2 = array("casa"=>2, "cafeina"=>array("ss"=>"dddd"), "oi2"=>5); 

//P.s 
print_r($treeWalker->getdiff($struct1, $struct2)) 

{ 
    new: { 
     b: "5", 
     oi: 5 
    }, 
    removed: { 
     oi2: 5 
    }, 
    edited: { 
     casa: { 
      oldvalue: 2, 
      newvalue: 1 
     }, 
     cafeina/ss: { 
      oldvalue: "dddd", 
      newvalue: "ddd" 
     } 
    }, 
    time: 0 
}