1

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.

1
  • 3
    The value of $file['meta'] is a string, not an array. Commented Nov 30, 2016 at 14:23

3 Answers 3

2

The value of $file['meta'] is a string, not an array. That means your approach to access the value does not work.

It looks like that meta value string is a json encoded object. If so you can decode it and then access the property "name" of the resulting object.

Take a look at this example:

<?php $file = [ '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' => [] ]; $fileMeta = json_decode($file['meta']); var_dump($fileMeta->name); 

The output obviously is:

string(12) "IMAG0161.jpg" 

In newer version of PHP you can simplify this: you do not have to store the decoded object in an explicit variable but can directly access the property:

json_decode($file['meta'])->name 

The output of this obviously is the same as above.

Sign up to request clarification or add additional context in comments.

1 Comment

For leaving a JSON obect as an object and not converting it to an array +1
1

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

Comments

0
<?php $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() ); $meta=$file['meta']; $json=json_decode($meta); echo $json->name; ?> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.