0

I have dynamic file which everytime i upload a file, its name depend on filename so jsonobj is example,

How can i echo $obj["FILENAME"] everytime the file change? I need a dynamic code

I try make echo $obj[0]["url"]; But it wont work,

$jsonobj = '{"File.png":{"name":"File.png","url":"www.example.com/File.png"}}';
$obj = (json_decode($jsonobj,true));
echo $obj["File.png"]["url"];

5
  • Why do you use the file name as a key if it's dynamic? Are you always going to have just one file inside that JSON? Commented May 20, 2021 at 9:11
  • To understand the data structure just do a simple print_r($obj) although as you have converted it to an array it would be better to call that $arr instead of $obj Commented May 20, 2021 at 9:13
  • A simple echo $obj['File.png']['name']; would work, but as @El_Vanja says, using the filename as the key makes this structure very unhelpful Commented May 20, 2021 at 9:16
  • Okay i tell u whole process. Im using woocommerce so i need to hook to API, So when i echo my variable such as $jsonobj it will show like that, so i need want to use cURL file, curl file need a url for uploaded image, so that why i to use dynamic. I dont know if got better solution to transfer $jsonobj to new CURLFILE 'Images' => new CURLFILE('www.example.com/File.png'), Commented May 20, 2021 at 9:50
  • 1
    Does this answer your question? Get the first element of an array Commented May 20, 2021 at 9:51

1 Answer 1

0

As your filename changes, the first key changes.

So first retrieve that key (File.png), then you can use it to output the content:

reset($obj);       // set pointer to first key
$key = key($obj);  // get first key (File.png)

$url = $obj[ $key ][ 'url' ];

But the comments on how impractical this is, still make sense.

Note As of PHP 7.3.0 you can use array_key_first() instead of reset(); key()

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

1 Comment

Why the complication? reset returns the first element, you can work with it directly: 3v4l.org/9XuRA Either way, the question seems a clear duplicate of just getting the first array element.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.