2016-04-18 16 views
1

meine JSON sieht derzeit wie dieseerstellen Stil von JSON-Objekt mit PHP

{ 
"customers": 
[ 
    { 
     "customer_id":3, 
     "customer_name":"Rick", 
     "Address":"333 North Road" 
    }, 
    { 
     "customer_id":4, 
     "customer_name":"Robby", 
     "Address":"444 North West Road" 
    } 
] 
} 

und ich würde es so aussehen mag diese

{ 
    "customers": 
    [ 
     { 
      "customer": 
      { 
       "customer_id":3, 
       "customer_name":"Rick", 
       "Address":"333 North Road" 
      } 
     }, 
     { 
      "customer": 
      { 
        "customer_id":4, 
        "customer_name":"Robby", 
        "Address":"444 North West Road" 
      } 
     } 
    ] 
} 

Es wird in diesem PHP-Skript erstellt werden, aber ich Ich bin mir nicht sicher, wie ich das Kundenattribut programmatisch jedem JSON-Objekt hinzufügen kann. Hilfe bitte?

//populate results 
$json = array(); 
$result = $stmt->get_result(); 
while ($row = $result->fetch_assoc()) { 
    $array = array(
      'customer_id' => $row['CustomerID'], 
      'customer_name' => $row['Name'], 
      'Address' => $row['Address'] 
     ); 
    array_push($json, $array); 
    foreach ($row as $r) { 

    } 
} 

$jsonstring = '{"customers":'. json_encode($json). "}"; 
return $jsonstring; 
+4

'$ array = array ("Kunde"=> Array (...));' –

+0

aber warum wollen Sie es ändern, ist die erste, besser – meda

+0

Ich versuche, bekomme die Syntax, um eine Lösung zu einem anderen Problem zu finden Ich muss versuchen, Möglichkeiten zu beseitigen. – john

Antwort

1
//populate results 
$json = array(); 
$result = $stmt->get_result(); 
while ($row = $result->fetch_assoc()) { 
    $array = array("customer" => array( // <-- change is here 
       'customer_id' => $row['CustomerID'], 
       'customer_name' => $row['Name'], 
       'Address' => $row['Address'] 
      ) 
     ); 
    array_push($json, $array); 
    foreach ($row as $r) { 

    } 
} 

$jsonstring = '{"customers":'. json_encode($json). "}"; 
return $jsonstring; 
+0

danke, das hat funktioniert. – john

+0

wenn es funktioniert, benutze "accept answer" :) –

+0

Ich musste warten, bis der Timer hochging. – john