Jump to content

Converting PHP array to Json


nbt725

Recommended Posts

Hello !

 

Can anybody help me converting PHP array to Json

 

I want actually following output thro' this php

 

{identifier:"name",

items: [{name:"Anytown", label:"Alaska"}]}

 

I tried following but not giving above.

 

$arr = array (identifier=>'name', items=>array(name=>'Anytown', label=>'Anytown'));

echo json_encode($arr);

 

but that does not generate [] but does generate {} for inner array.

 

Actually this json passes to Ajax Javascript handler for Dojo combobox.

 

Please help.

 

Thanks in Advance !

 

Nbt

Link to comment
https://forums.phpfreaks.com/topic/169357-converting-php-array-to-json/
Share on other sites

No, it gives following :

 

{"identifier":"name","items":{"Champaign":"Champaign","Chicago":"Chicago"}}

 

but we need :

 

{identifier:"name",

items: [

{name:"Anytown", label:"Alaska"}

]}

 

And in php 5.2 json_encode() is given which also I tried.

 

Thanks in Advance !

 

Nbt

 

 

Hello !

 

Can anybody help me converting PHP array to Json

 

I want actually following output thro' this php

 

{identifier:"name",

items: [{name:"Anytown", label:"Alaska"}]}

 

I tried following but not giving above.

 

$arr = array (identifier=>'name', items=>array(name=>'Anytown', label=>'Anytown'));

echo json_encode($arr);

 

but that does not generate [] but does generate {} for inner array.

 

json_encode should work and you are correct that it does not produce the square brackets that's because it's a javascript object not a javascript array

Yea But I need as per mentioned style with [] not {} as Dojo Combobox needs that style. This echo json string with [] is received by Dojo javascript response handler function which gets binded to store to populate combobox dynamically.

 

So please guide me, how should I do it ?

 

Thanks in advance !

 

nbt

Re-reading the json i see something now.

 

Ok to make it more readable let's indent it

your Json notation

{
"identifier":"name",
"items":{
	"Champaign":"Champaign",
	"Chicago":"Chicago"
}
}

Desired json notation:

{
identifier:"name",
items: 
[
	{name:"Anytown", label:"Alaska"}
]
}

 

In the above Json code its still a js object. hover the items inside this object is an array which means you can you store more names inside the items.

your php array creation should be something like so:

 

<?php
$arr = array (
identifier=>'name', 
items=>array(
	array('name'=>'Anytown', 'label'=>'Anytown'),
	array('name'=>'Second', 'label'=>'Second')
)
);

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.