Martijn Michel
Martijn Michel

Reputation: 39

Get value from array with php/json

Im trying to read a value of an ajax send jsonarray to base my filename upon but i cant seem to figure out how to read the value.

my php;

$postdata = $_POST['data'];

$jsondata = json_decode($postdata);
$myname = $jsondata->name;

$dir = 'users/'.$myname.'/desktop-'.$myname.'.json';

json array looks like this;

[{"name":"mmichel"},
 {"myicons":
    [{"icon":
       [{"name":"homepagelink","rel":"http://test.tocadovision.nl","id":"icon1","class":"icon bookmark"}]
     },
     {"icon":
       [{"name":"aboutpagelink","rel":"http://test.tocadovision.nl","id":"icon2","class":"icon bookmark"}]
    }]
}]

hope someone can tell me what im doing wrong.. must be rly easy i guess

Upvotes: 0

Views: 50

Answers (2)

raj
raj

Reputation: 817

Ensure you have json enabled in your php config. You can do this by doing

<?php
phpinfo();

This should output something like this which indicates json module is enabled. If you don't have this enabled, enable it.

enter image description here

Make sure you have the correct valid json string in $json variable and use one of the following methods.

$arr = json_decode($json, true);
print_r($arr[0]['name']);


$arr = json_decode($json);
print_r($arr[0]->name);

Upvotes: 0

BenM
BenM

Reputation: 53246

Since $jsondata contains an array of one object, you need to access the first element of the array in your assignment:

$myname = $jsondata[0]->name;

Upvotes: 1

Related Questions