这是JSON应该如何,或者它在空间方面是否更优化?

时间:2015-07-20 16:24:06

标签: javascript php json wordpress

在我的代码中我有

var team = <?php echo json_encode(get_results("SELECT id,name,title,bio,sord,picfn FROM mems ORDER BY sord")); ?>;

生成像

这样的对象的JavaScript数组
var team = [{"id":"1","name":"somename1","title":"sometitle1","somebio1":"...","sord":"69","picfn":"somepicfn1"},{"id":"2","name":"somename2","title":"sometitle2","bio":"sometitle2","sord":"3","picfn":"somepicfn2"},...];

对我而言,重复字段名称"id""name""title""bio&#34;,"sord",{似乎效率很低{1}}在数组的每个对象中。让数组中的对象只是字段的值更有效率,例如。

"picfn"

并且具有将键映射到索引的单独结构,例如

{"1, "somename", "sometitle1", "someboi1", "1", "somepicfn1"}

???

或者有什么重要的东西我在这里失踪了吗?

2 个答案:

答案 0 :(得分:0)

Json是一个字符串,所以你无法真正优化它。 每次你有一个元素时,你必须提供每个键/值。

哦,顺便说一句,不要直接在js中放置查询结果,请稍微分开你的代码,使用变量......

答案 1 :(得分:0)

您可以将列名和值分开,例如:

json_encode( [
    'columns'   => array_keys( $team[0] ),
    'values'    => array_map( function( $v ) { 
        return array_values( $v ); 
    }, get_results( "SELECT id,name,title,bio,sord,picfn FROM mems ORDER BY sord" ) )
] );

/* output:
{"columns":["id","name","title","bio","sord","picfn"],"values":[["1","somename1","sometitle1","sometitle1","69","somepicfn1"],["2","somename2","sometitle2","sometitle2","3","somepicfn2"],["3","somename3","sometitle3","sometitle3","4","somepicfn3"]]}
*/