2009-09-16 18 views

risposta

10

Il modo più semplice sarebbe probabilmente iniziare con un array associativo delle coppie che si desidera:

$data = array("myfirstvalue" => "myfirsttext", "mysecondvalue" => "mysecondtext"); 

quindi utilizzare un foreach e alcuni concatenazione di stringhe :

$jsontext = "["; 
foreach($data as $key => $value) { 
    $jsontext .= "{oV: '".addslashes($key)."', oT: '".addslashes($value)."'},"; 
} 
$jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma 
$jsontext .= "]"; 

Oppure, se si dispone di una versione recente di PHP, è possibile utilizzare il functi codifica jSON integrato: basta fare attenzione a quali dati si passano per farlo corrispondere al formato previsto.

+0

Questo ha funzionato come un incantesimo grazie. Anche se ho capito bene avrei dovuto usare "json_encode" sarebbe stato meglio programmare? – Haluk

+2

Perché non usare semplicemente json_encode? –

+0

@TimWachter Questa risposta è del 2009; nota il bit alla fine su "se hai una versione recente"; un discreto numero di host stava ancora eseguendo solo PHP 4 (e 'json_encode' è stato introdotto in 5.2). – Amber

60

Una volta che hai i dati di PHP, è possibile utilizzare la funzione json_encode; è fornito in bundle con PHP a partire da PHP 5.2

Nel tuo caso si stringa JSON rappresenta:

  • una lista contenente 2 elementi
  • ciascuno essere un oggetto, contenente 2 immobili/Valori

In PHP, ciò creerebbe la struttura che si sta rappresentando:

$data = array(
    (object)array(
     'oV' => 'myfirstvalue', 
     'oT' => 'myfirsttext', 
    ), 
    (object)array(
     'oV' => 'mysecondvalue', 
     'oT' => 'mysecondtext', 
    ), 
); 
var_dump($data); 

Il var_dump si ottiene:

array 
    0 => 
    object(stdClass)[1] 
     public 'oV' => string 'myfirstvalue' (length=12) 
     public 'oT' => string 'myfirsttext' (length=11) 
    1 => 
    object(stdClass)[2] 
     public 'oV' => string 'mysecondvalue' (length=13) 
     public 'oT' => string 'mysecondtext' (length=12) 

E, la codifica a JSON:

$json = json_encode($data); 
echo $json; 

Si ottiene:

[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}] 


BTW: Frolm quello che mi ricordo, direi la tua stringa JSON non è valida-dati JSON: dovrebbero esserci virgolette attorno alla stringa, compresi i nomi delle proprietà degli oggetti

Vedere http://www.json.org/ per la grammatica.


Spero che questo aiuti :-)

+2

In realtà non c'è bisogno di gettare le matrici in oggetti. json_encode calcolerà automagicamente che dovrebbe rappresentare le cose come un oggetto se si hanno chiavi di stringa. –

+1

Hi, L'output che ho ricevuto dal codice precedente è in realtà diverso: array (2) {[0] => oggetto (stdClass) # 1 (2) {["oV"] => stringa (12) "myfirstvalue" ["oT"] => string (11) "myfirsttext"} [1] => object (stdClass) # 2 (2) {["oV"] => string (13) "mysecondvalue" ["oT "] => string (12)" mysecondtext "}} [{" oV ":" myfirstvalue "," oT ":" myfirsttext "}, {" oV ":" mysecondvalue "," oT ":" mysecondtext "}] – Haluk

+1

Ho rimosso var_dump dal codice precedente e ho modificato la parte principale come segue. Ora funziona benissimo: $ data = array ( array ( oV => 'myfirstvalue', oT => 'myfirsttext', ), array ( oV => 'mysecondvalue', oT => 'mysecondtext', ), ); – Haluk

2

Questo è il codice php per generare formato JSON

<?php 

    $catId = $_GET['catId']; 
    $catId = $_POST['catId']; 

    $conn = mysqli_connect("localhost","root","","DBName"); 
    if(!$conn) 
    { 
     trigger_error('Could not Connect' .mysqli_connect_error()); 
    } 

    $sql = "SELECT * FROM TableName"; 
    $result = mysqli_query($conn, $sql); 

    $array = array(); 

    while($row=mysqli_fetch_assoc($result)) 
    { 
     $array[] = $row; 
    } 

    echo'{"ProductsData":'.json_encode($array).'}'; //Here ProductsData is just a simple String u can write anything instead 
    mysqli_close('$conn'); 
?>