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. charAt和String的用法

    package charpter2; import java.util.Scanner; public class Test { public static void main(String[] ar ...

  2. Promise in Chakra

    http://www.ecma-international.org/ecma-262/#sec-fulfillpromise 25.4.1.3.1 and 25.4.1.3.2 Promise Rej ...

  3. socket.shutdownOutput()方法

    我在用客户端给服务端发报文的时候,一开始客户端没有调用这个方法,结果服务端使用SAX解析报文的时候,public void endDocument() throws SAXException总是得不到 ...

  4. day17--JQuery

        JQuery(中文社区:http://jquery.cuishifeng.cn/) 模块  类库  在不同语言叫法不一样而已 DOM/BOM/JavaScript的类库 一.查找元素 JQue ...

  5. NodeMCU入门(1):刷入At固件,透传数据到TcpServer和Yeelink平台

    准备工作 1. NodeMCU  LUA ESP8266 CP2102  WIFI Internet Development Board,仔细看背面可以看出自带cp2102模块,可以通过普通的手机充电 ...

  6. 关于SSH不能连接及报错的问题总结

    前言 此文不涉及到因网络.防火墙设备而导致的SSH不能访问.运维常见问题,这里不做过多的讲解,主要讲讲出了大家所知道的,还有其他什么原因会导致SSH无法访问呢?好了,那么,如果想知道的话,那就继续往下 ...

  7. BZOJ3064 Tyvj 1518 CPU监控 线段树

    欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ3064 题意概括 一个序列,要你支持以下操作: 1. 区间询问最大值 2. 区间询问历史最大值 3. ...

  8. vi中批量加注释

    用v进入virtual模式 按Control+v(win下面ctrl+q)进入列模式 上下键来进行选择 I进行输入(shift+i) 按两次ese键

  9. 【Java】 剑指offer(57-1) 和为s的两个数字

      本文参考自<剑指offer>一书,代码采用Java语言. 更多:<剑指Offer>Java实现合集   题目 输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它 ...

  10. IPV4闪退

    如果出现这种状况,在安全模式下重注册dll 运行->输入cmd->输入 for %1 in (%windir%\system32\*.dll) do regsvr32.exe /s %1 ...