Home >Backend Development >PHP Tutorial >How to build JSON format and new array in php

How to build JSON format and new array in php

WBOY
WBOYOriginal
2016-07-25 09:03:44914browse
  1. function RecordToJson($recordset)
  2. {
  3. $jstr='[';
  4. while($rs = $recordset->Fetch())
  5. {
  6. //$nick = iconv ("GBK",'utf-8',$rs['nick']);/*Convert to utf-8 encoding*/
  7. //TODO: Traverse the result set
  8. $arr_keys=array_keys($rs);
  9. $ jstr=$jstr.'{';
  10. for($i=0;$i{
  11. //The database encoding is gbk, the encoding needs to be converted
  12. //TODO;iconv ("GBK",'utf-8',$rs['nick']);/*Convert to utf-8 encoding*/
  13. $key=iconv("GBK",'utf-8',$arr_keys[$ i]);//$arr_keys[$i];
  14. $value=iconv("GBK",'utf-8',$rs[$arr_keys[$i]]);//$rs[$arr_keys[$ i]];
  15. $jstr=$jstr.'"'.$key.'":"'.$value.'",';
  16. }
  17. $jstr=substr($jstr,0,strlen($jstr) -1);
  18. $jstr=$jstr.'},';
  19. }
  20. $jstr=substr($jstr,0,strlen($jstr)-1);
  21. $jstr=$jstr.']';
  22. return $jstr;
  23. }
Copy code

php’s default result set array has a numeric index. The following function can remove the numeric index and only keep the field index:

  1. function RebuilderRecord( $recordset)
  2. {
  3. $row=0;
  4. while($rs = $recordset->Fetch())
  5. {
  6. //TODO: Traverse the result set
  7. $arr_keys=array_keys($rs);
  8. for($ i=0;$i
  9. {
  10. $newrs[$row][$arr_keys[$i]]=$rs[$arr_keys[$i]];
  11. }
  12. $row++;
  13. }
  14. return $newrs;
  15. }
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn