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. canvas抛物线运动轨迹

    本来是想做一个贝塞尔曲线运动轨迹的 公式太复杂了,懒得算,公式在最后 我先画了一个抛物线,我确定了两个点,起点(0,0),终点(200,200) 用坐标系可算出方程 y=-0.005x^2 现在找出终 ...

  2. Rookey.Frame v1.0快速开发平台-整体介绍

    Rookey.Frame v1.0是一套基于.NET MVC的极速开发框架,支持简单逻辑模块零代码编程.支持二次开发,具有高扩展性.高复用性.高伸缩性. 框架特点 (1)简单逻辑模块实现零代码编程,通 ...

  3. Linux && 与 ||

    一.&& && 表示前一条命令执行成功时,才执行后一条命令 ,如 echo '1‘ && echo '2' || 表示上一条命令执行失败后,才执行下一条 ...

  4. floor()函数 和round()函数的区别

    floor()函数 和round()函数的区别 2018-08-17  09:40:00 1.floor()函数:取整,保留整数部分,舍弃小数部分. 2.round()函数:四舍五入.round(x, ...

  5. KNN分类算法及python代码实现

    KNN分类算法(先验数据中就有类别之分,未知的数据会被归类为之前类别中的某一类!) 1.KNN介绍 K最近邻(k-Nearest Neighbor,KNN)分类算法是最简单的机器学习算法. 机器学习, ...

  6. 6-6 小球下落 uva679

    较为简单的找规律题目 开始认识二叉树  虽然这题和二叉树没有啥关系 #include<bits/stdc++.h> using namespace std; int main() { in ...

  7. 微信小程序开发--第一个项目

    一:Hello World 1.AppId 2.打开开发者工具 3.显示效果 二:

  8. Eclipse添加git插件上传项目到github

    前提: 在Github已经注册成功自己的账号 新建一个仓库 创建成功后记住url: 首先像安装Pydev一样 点击help的Install New Software 点击Add后添加链接http:// ...

  9. 素数筛选-hdu1262

    题目描述: 代码实现: #include<stdio.h> using namespace std; ]; void sieve(int n) { ;i<;i++) prime[i] ...

  10. 解决Ubuntu无法进行SSH连接的问题(以及如何使用SSH)

    我们在VM中安装好Ubuntu 虚拟机后,经常需要使用Xshell.ssh等工具进行远程连接,方便我们在两个操作系统中进行文件的复制与移动,但是有时候会出现无法连接的问题,原因可能是Ubuntu中默认 ...