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"];

Rusydi
  • 1
  • 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? – El_Vanja May 20 '21 at 09: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` – RiggsFolly May 20 '21 at 09: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 – RiggsFolly May 20 '21 at 09: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'), – Rusydi May 20 '21 at 09:50
  • Does this answer your question? [Get the first element of an array](https://stackoverflow.com/questions/1921421/get-the-first-element-of-an-array) – El_Vanja May 20 '21 at 09:51

1 Answers1

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

Michel
  • 4,076
  • 4
  • 34
  • 52
  • Why the complication? `reset` returns the first element, you can work with it directly: https://3v4l.org/9XuRA Either way, the question seems a clear duplicate of just getting the first array element. – El_Vanja May 20 '21 at 09:52