2015-08-20 23 views
0

I'm通過Ajax發送一個JavaScript對象與此structrucePHP json_decode無序陣列

[ 
    { name:'box', price:'20', id:'72', units : 2 }, 
    { name:'box2', price:'30', id:'73', units : 2 }, 
    { name:'box3', price:'40', id:'74', units : 2 } 
] 

獲取服務器上的數據這樣

$data = json_decode(file_get_contents("php://input"),true); 
$queryconst = ''; 
foreach($data as $key => $value){ 
    $format[$key] = $value; 
    $format_keys = array_keys($format[$key]); 
    $newArray = $this->slashesToArray($value); 
    $queryconst = $queryconst.'(\''.implode("','", $newArray).'\'),';   
} 
$queryconst = rtrim($queryconst, ","); 
$query = "INSERT INTO format (".implode(",", $format_keys).") VALUES ".$queryconst; 

如果I`M發送數據具有單個對象

[ 
    { name:'box', price:'20', id:'72', units : 2 } 
] 

一切工作正常

$query = INSERT INTO format (name,units,price,id) VALUES ('box','2','20','72') 

的問題是當該數據具有多個對象

[ 
    { name:'box', price:'20', id:'72', units : 2 }, 
    { name:'box2', price:'30', id:'73', units : 2 }, 
    { name:'box3', price:'40', id:'74', units : 2 } 
] 

和查詢

$query = INSERT INTO format (price,name,units,product_id) 
     VALUES ('box','2','20','74'),('30','box2','2','74'),('40','box3','2','74') 

FO所述第一對象的順序是從靜止不同和查詢失敗

任何線索?

回答

1

最後,我已經解決了,只是排序數組在循環的開頭

$data = json_decode(file_get_contents("php://input"),true); 
$queryconst = ''; 
foreach($data as $key => $value){ 
    ksort($value); 
    $format[$key] = $value; 
    $format_keys = array_keys($format[$key]); 
    $newArray = $this->slashesToArray($value); 
    $queryconst = $queryconst.'(\''.implode("','", $newArray).'\'),';   
} 
$queryconst = rtrim($queryconst, ","); 
$query = "INSERT INTO format (".implode(",", $format_keys).") VALUES ".$queryconst; 
0

JSON對象是無序。規範或任何實現中的任何內容都不會在迭代,編碼或解碼JSON對象時保證任何特定順序。您必須顯式使用對象鍵名稱,而不是隱式地依賴它們的順序。

這些方針的東西:

$data = json_decode(file_get_contents("php://input"), true); 

// this is your whitelisting against column injection 
$allowedColumns = ['name', 'price', ...]; 
$columns = array_keys($data[0]); 
if (array_diff($columns, $allowedColumns)) { 
    throw new InvalidArgumentException; 
} 

$values = []; 
foreach ($data as $row) { 
    // this maps the values to the column names in the right order, including escaping 
    $values[] = array_map(function ($column) use ($row) { 
     return sprintf("'%s'", mysql_real_escape_string($row[$column])); 
    }, $columns); 
} 

$query = sprintf(
    'INSERT INTO (%s) VALUES %s', 
    join(', ', $columns), 
    join(', ', array_map(function ($row) { 
     return sprintf('(%s)', join(', ', $row)); 
    }, $values)) 
); 

注意正確轉義使用mysql_real_escape_string。另請注意,這已被棄用,您應該使用帶有佔位符和參數綁定的PDO或mysqli代替。