array2json is a PHP function that will convert the array given as its argument into a JSON string. The created JSON string will be returned. This is very useful in Ajax apps using JSON over XML. If you are using XML, you better off using my xml2array() JavaScript function.

Note: This is an old function - if you use a new version of PHP(5.2 or newer) you will get the json_encode() function. That can be used to convert arrays to a JSON string.

Usage

First you need a PHP array. For example...

$data = array(
'success' => "Sweet",
'failure' => false,
'array' => array(),
'numbers' => array(1,2,3),
'info' => array(
'name' => 'Binny',
'site' => 'http://www.openjs.com/'
)
);

Provide this array as the argument of the array2json() function...

$json = array2json($data);

The resulting string will be(actual output - the source says print array2json($data);)...


{"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}}

I am formatting the output for better readability...

{
"success":"Sweet",
"failure":false,
"empty_array":{},
"numbers":[1,2,3],
"info":{
"name":"Binny",
"site":"http://www.openjs.com/"
}
}

Handled Data types

All the basic data types are handled...

  • String
  • Numbers
  • Boolean(true/false)
  • Numerical Array
  • Associative Array

Objects are not handled for obvious reasons.

Code

<?php 
function array2json($arr) { 
    if(function_exists('json_encode')) return json_encode($arr); //Lastest versions of PHP already has this functionality. 
    $parts = array(); 
    $is_list = false;

//Find out if the given array is a numerical array 
    $keys = array_keys($arr); 
    $max_length = count($arr)-1; 
    if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1 
        $is_list = true; 
        for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position 
            if($i != $keys[$i]) { //A key fails at position check. 
                $is_list = false; //It is an associative array. 
                break; 
            } 
        } 
    }

foreach($arr as $key=>$value) { 
        if(is_array($value)) { //Custom handling for arrays 
            if($is_list) $parts[] = array2json($value); /* :RECURSION: */ 
            else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */ 
        } else { 
            $str = ''; 
            if(!$is_list) $str = '"' . $key . '":';

//Custom handling for multiple data types 
            if(is_numeric($value)) $str .= $value; //Numbers 
            elseif($value === false) $str .= 'false'; //The booleans 
            elseif($value === true) $str .= 'true'; 
            else $str .= '"' . addslashes($value) . '"'; //All other things 
            // :TODO: Is there any more datatype we should be in the lookout for? (Object?)

$parts[] = $str; 
        } 
    } 
    $json = implode(',',$parts); 
     
    if($is_list) return '[' . $json . ']';//Return numerical JSON 
    return '{' . $json . '}';//Return associative JSON 

array2json() - Convert PHP arrays to JSON的更多相关文章

  1. Convert List<Entity> to Json String.

    public static string ToJson(this object obj, string datetimeformats) {     var timeConverter = new I ...

  2. Convert JS object to JSON string

    Modern browsers (IE8, FF3, Chrome etc.) have native JSON support built in (Same API as with JSON2). ...

  3. spring cloud oauth2+JWT整合使用token返回JWT Cannot convert access token to JSON解决办法

    我碰到的问题是Token正常,但是资源访问不了,原因是,资源服务配置的时候需要传一个对象: 设置了这个就可以了

  4. PostgreSQL JSON函数

    https://www.postgresql.org/docs/9.6/static/functions-json.html PostgreSQL 9.6.1 Documentation Prev U ...

  5. json深度详解及org.json库

    了解json  (Javascript Object Notation) 网站:http://json.org/ english JSON (JavaScript Object Notation) i ...

  6. Jackson学习二之集合类对象与JSON互相转化--转载

    原文地址:http://lijingshou.iteye.com/blog/2003059 本篇主要演示如何使用Jackson对List, Map和数组与JSON互相转换. package com.j ...

  7. Create JSON by Jackson API(转)

      原文地址: Create JSON by Jackson API Jackson API is a multi-purpose Java library for processing JSON. ...

  8. postgres json

    https://www.postgresql.org/docs/9.6/static/functions-json.html Search Documentation:  Home → Documen ...

  9. json相关类库,java对象与json相互转换

    有效选择七个关于Java的JSON开源类库 转自:http://www.open-open.com/lib/view/open1397870197828.html 翻译: (英语原文:http://w ...

随机推荐

  1. 步步为营-70-asp.net简单练习(文件的上传和下载)

    大文件的上传一般通过FTP协议,而一般小的文件可以通过http协议来完成 1 通过asp.net 完成图片的上传 1.1 创建html页面 注意:1 method="post" ; ...

  2. 基于Linux平台的自动化运维Devops-----之自动化系统部署

    一.自动化运维的背景网站业务上线,需要运维人员在短时间内完成几百台服务器部署,包括系统安装.系统初始化.软件的安装与配置.性能的监控......所谓运维自动化,即在最少的人工干预下,利用脚本与第三方工 ...

  3. 事件方法on()

    on()方法用来处理事件.jQuery会处理所有浏览器的兼容性问题. on()方法可以指定影响哪个事件,相当于JavaScript中的addEventListener()事件监听. on()方法有两个 ...

  4. Ext.js入门:Window对象与FormPanel(六)

    一:Ext.Window类 二:Ext.Window类实例 三:Ext.FormPanel类 四:Ext.FormPanel类实例   1.类Ext.Window 包: Ext 定义的文件 Windo ...

  5. ubuntu ufw防火墙软件的配置入门

    顺便,一条龙作完安全吧. ufw的使用,是比iptables简单.但只能作简单的事儿,更改简单的netfilter里的iptable里的记录.难点的,可能还是得iptables原生命令. 自打2.4版 ...

  6. 026 使用大数据对网站基本指标PV案例的分析

    案例: 使用电商网站的用户行为日志进行统计分析 一:准备 1.指标 PV:网页流浪量 UV:独立访客数 VV:访客的访问数,session次数 IP:独立的IP数 2.上传测试数据 3.查看第一条记录 ...

  7. 洛谷 P2440 木材加工【基础二分】

    题目链接:https://www.luogu.org/problemnew/show/P2440 题目描述 木材厂有一些原木,现在想把这些木头切割成一些长度相同的小段木头(木头有可能有 剩余),需要得 ...

  8. windows server 2003 安全加固(二)

    windows server 2003 安全加固 关闭默认端口 我们知道远程桌面服务端口默认开启在3389端口,如果我们一定要用到,最好能换到另外的端口上,放到靠后的端口号上去,比如10001. 更改 ...

  9. 论文--Topic-Sensitive PageRank

    背景 原有的PageRank方法:通过web上链接结构信息得到页面之间相对的重要性,和特定的查询内容无关 论文涉及到的其他算法 HITS Hilltop,处理常见的流行查询 popular query ...

  10. 【NOIP2018】【RP++!】【神大退役记+一丢丢回忆录】

    emmm初赛都完了啊,还有20多天的样子退役选手又要++++++了 所以在这里先预祝各路dalao取得好成绩!! 手动艾特亲友$@Abyssful@阿澈说他也想好好学习@Ed\_Sheeran@歪瓜是 ...