Baz Baz - 9 days ago 6
PHP Question

Getting a value from associative arrays PHP

I have an array..

$file=array(
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => array()
)


and I am trying to extract the name using

$fileName = $file['meta'['name'];


which gives me a Illegal string offset 'name' error.

Answer

This is happening because your meta is a json, so you should decode and then access whatever you need, not that I placed true as second parameter becuase i wanted to decode as an associative array instead of an object

$decoded = json_decode($file['meta'],true);
echo $decoded['name'];
//print IMAG0161.jpg

You can check a live demo here

But you can easily access as an obect

$decoded = json_decode($file['meta']);
echo $decoded->name;
//print IMAG0161.jpg

You can check a live demo here