简体   繁体   中英

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

由于$jsondata包含一个对象的数组,因此您需要访问分配中的数组的第一个元素:

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

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.

在此处输入图片说明

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM