2016-06-06 18 views
1

ich ein json Ausgabeformat wie diesePHP JSON Encode: Formatierung

{ 
    "data": 
    [ 
     ["FAMILY: Isopropyl Alcohol 250ml","32.34"], 
     ["AMBROXOL Expel 6mg-mL 15ML Drops","75.04"] 

    ] 

} 

Allerdings haben wollte, es zeigt anders als wollte. Die ersten Elemente werden weiterhin repliziert. Das Ergebnis ist:

{ 
"data": 
[ 
    ["FAMILY: Isopropyl Alcohol 250ml","32.34"], 
    ["FAMILY: Isopropyl Alcohol 250ml","32.34","AMBROXOL Expel 6mg-mL 15ML Drops","75.04"] 

] 

} 

Das ist mein PHP-Code:

foreach ($this->cases_model->test() as $row)  { 

       $new_row[]=$row['name']; 
       $new_row[]=$row['dp']; 
       $row_set['data'][] = $new_row; //build an array 
      } 

     echo json_encode($row_set); //format the array into json data 

Antwort

4

$new_row nicht gelöscht wird, so dass er die Daten der vorherigen Iteration hält. So ändern Sie Ihre foreach zu:

foreach ($this->cases_model->test() as $row){ 
    $new_row = []; //Reset the array for every loop 
    $new_row[]=$row['name']; 
    $new_row[]=$row['dp']; 
    $row_set['data'][] = $new_row; //build an array 
} 
1
foreach ($this->cases_model->test() as $row)  { 

    $new_row[]=$row['name']; 
    $new_row[]=$row['dp']; 
    $row_set['data'][] = $new_row; //build an array 
    $new_row = NULL;  
}