2013-07-01 46 views
1

我在查找如何从MySQL查询中获取JSON结果时遇到了一些麻烦;把它们变成一个PHP数组;从该数组中删除相同的字段,并将该数组重新转换为JSON。 [1]是其中包含实际JSON的行的一部分。将JSON解码为PHP数组,删除相同的条目并编码回PHP

我错过了什么吗?无法在网站上找到任何类似的问题。谢谢!

$data = mysql_fetch_row($result); 
print_r($data); 

$json = json_decode($data[1], TRUE); 
var_dump($json); 
print_r($json); 

$distinctresult = array_unique($json); 
print_r($distinctresult); 

$final = json_encode($distinctresult); 


{"rows":[{"level":"ERROR","key":"Standard Not found","value":"RI.1.8"},{"level":"ERROR","key":"Standard Not found",{"level":"ERROR","key":"Standard Not found","value":"RI.K.9"},{"level":"ERROR","key":"Standard Not found","value":"RI.K.9"},{"level":"ERROR","key":"Standard Not found","value":"RI.K.9",}]} 

这里的MySQL查询我使用的是:

"select distinct d.valueField 
    from etllogs t 
    inner join etllogdetails d on t.uid = d.etllogID and d.valueField like '%ERROR%' 
    where t.transformationName like 'CM Data Extract' 
    and (t.timestamp >= (now() - interval 24 hour)) 
    order by t.timestamp desc;"; 
+1

什么不起作用?你的阵列中有几个级别? – Savageman

+0

“删除相同的字段”是什么意思?如果不知道你的JSON是什么样子的话,这个问题是毫无意义的。 – Jon

+0

我没有看到任何逻辑错误。向我们展示print_r的结果 – user4035

回答

1

似乎您试图访问数组元素的JSON编码字符串($data[1])。
我有下面的代码的成功:

$data = array(0=>array('column1'=>'value1','column2'=>'value2'), 
       1=>array('column3'=>'value3','column4'=>'value3')); 

$data_json=json_encode($data); 
echo"ORIGINAL JSON:<pre>".print_r($data_json,true)."</pre>"; 

$data_php=json_decode($data_json,true); 
echo"PHP ARRAY:<pre>".print_r($data_php,true)."</pre>"; 

$data_chunk=$data_php[1]; 
echo"PHP ARRAY CHUNK:<pre>".print_r($data_chunk,true)."</pre>"; 

$distinctresult = array_unique($data_chunk); 
echo"UNIQUE CHUNK:<pre>".print_r($distinctresult,true)."</pre>"; 

$final = json_encode($distinctresult); 
echo"FINAL JSON:<pre>".print_r($final,true)."</pre>"; 

http://phpfiddle.org/main/code/7dg-nnb