2014-12-02 24 views
0

我有一个HTML页面,该页面在PHP中创建新的字符串JSON,当我提交表单我送AJAX的数据是这样的:从Ajax调用

array(7) { ["idfornitore"]=> string(1) "1" ["criterio-5"]=> string(1) "4" ["voto-5"]=> string(1) "1" ["parziale-5"]=> string(1) "4" ["criterio-3"]=> string(1) "2" ["voto-3"]=> string(1) "3" ["parziale-3"]=> string(1) "6"} 

例子:

["criterio-5"] => string(1) "4" ["voto-5"]=> string(1) "1" ["parziale-5"]=> string(1) "4" 
["criterio-5"] => is "weight of criterio5" 
["voto-5"]  => is "value of criterio5" 
["parziale-5"] => is "totale of criterio5" (weight * value) 

我的服务PHP这样做:

$totale = 0; 
foreach ($_POST as $key => $value) { 
    if (strstr($key, "parziale")) { 
     $totale = $totale + $value; 
    } 
} 

==================================

我会scorrermi阵列并形成如此“做了​​一个JSON字符串:

{  
    "parziali": [ 
     {"idcriterio": "5", "peso": "4" , "voto": "1", "parziale": "5" }, 
     {"idcriterio": "3", "peso": "2" , "peso": "3", "peso": "6" } 
    ] 
} 

我该怎么办?

+2

我不知道你打算如何从你的foreach函数计算出一个总的JSON字符串。 – Ohgodwhy 2014-12-02 17:34:21

回答

0

这类似于建立XML元素 - 建立{搜索标准,博托,parziale},其中标签为后缀的搜索标准值的元组

$tuples = array(); 
foreach ($input as $key => $value) { 
    list($field, $suffix) = explode($key); 
    if ($field === 'idcriterio') { 
     $tuples[$suffix] = $suffix; 
     $tuples['peso'] = $value; 
    } 
    else { 
     $tuples[$suffix][$field] = $value; 
    } 
} 

$json = json_encode($tuples); 

我不明白怎么parziale计算,但你得到的想法