Saturday 23 April 2011

PHP array to Javascript array format

Just been messing around with ajax and a particular jQuery plugin... The easiest way to convert a PHP array to a Javascript array is to use the json_encode() function (PHP 5.2+).

<?php 
echo json_encode(array("One","Two","Three"));
?>

This will output the Javascript array notation:

["One","Two","Three"]

If I use an ordered map array like this:

<?php 
echo json_encode(array("1"=>"One","2"=>"Two","3"=>"Three"));
?>


It will convert it to a Javascript object:

{"1":"One","2":"Two","3":"Three"}

2 comments:

  1. But how about this, how to convert the php array format to javascript array format in the following ? I would appreciate any help.

    $(document).ready(function()
    {
    $(".btytp").bt();
    fill: '#F4F4F4',
    strokeStyle: '#666',
    spikeLength: '20',
    spikeGirth: '10',
    width: 350,
    cornerRadius: 0,
    cornerPointY: 1,
    strokeWidth: 0,
    cssStyles: {
    fontFamily: '"Lucida Grande",Helvetica,Arial,Verdana,sans-serif',
    fontSize: '12px',
    padding: '10px 14px'
    },
    shadow: true,
    shadowColor: 'rgba(0,0,0,.5)',
    shadowBlur: 8,
    shadowOffsetX: 4,
    shadowOffsetY: 4,
    shadowBlur: 8,
    );

    ReplyDelete
    Replies
    1. That javascript is not a datatype or json-parsable object but rather raw javascript code syntax. There no way to get this into php the way it is now unless you write a parser and decide what you want it to do when it can't figure put what the php equivalent of bits of that code is. Or, manually pull out the json-style bits and json_decode them into your php script.

      Delete