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. 《转》Java与Http协议

    引言 http(超文本传输协议)是一个基于请求与响应模式的.无状态的.应用层的协议,常基于TCP的连接方式.HTTP协议的主要特点是:     1.支持客户/服务器模式.     2.简单快速:客户向 ...

  2. 攻击图生成工具mulval的安装和配置

    https://doc.mbalib.com/view/8620168b35e50fbe9b005fee33c192ad.html http://www.bingbig.com/227.html

  3. hihocoder 1343 : Stable Members【拓扑排序】

    hihocoder #1343:题目 解释:一个学习小组,一共有N个学员,一个主管.每个学员都有自己的导师(一个或者多个),导师可以是其他学员也可以是主管.每周学员都要把自己的学习报告和收到的报告提交 ...

  4. Scrapy爬虫学习笔记 - 爬虫基础知识

    一.正则表达式 二.深度和广度优先                                三.爬虫去重策略

  5. QMessageBox的用法

    QMessageBox的用法   先来看一下最熟悉的QMessageBox::information.我们在以前的代码中这样使用过:   QMessageBox::information(NULL,  ...

  6. HDU 3625 Examining the Rooms【第一类斯特灵数】

    <题目链接> <转载于 >>> > 题目大意:有n个锁着的房间和对应n扇门的n把钥匙,每个房间内有一把钥匙.你可以破坏一扇门,取出其中的钥匙,然后用取出钥匙打 ...

  7. wireshark实战之局域网抓包分析

    Wireshark.它是一款本地监听数据的大杀器,弊端是只能监听本地的数据,有什么办法可以让局域网中的流量都从本机走呢? 第一ARP嗅探,劫持网关,再本地抓包. 第二交换机镜像端口,在路由或者交换机处 ...

  8. Flag之2019年立

    今天是2019年1月12日,这是我第一次在一个公众的平台上立flag. 至于为何想立一个flag,应该是因为自己年龄渐长,从儿时读书时代家人对自己的要求就不高,考试可以及格即可,导致了自己养成了比较安 ...

  9. 启动Azure模拟器出错解决方案

    错误弹窗: 输出控制台: Microsoft Azure Tools: Warning: Overriding public port 80 to 2888 in role 'WebRole1'. M ...

  10. XenServer日志清理方法

    服务器使用时间长了,XenServer产生了很多日志,甚至有些人因为日志占满了空间, 导致系统出现问题:xapi崩溃,或者系统卡死,重启也无效. 所以我们要时常看看日志是否占的空间的,清理下日志先查看 ...