-1

I am trying to pull JSON data path stored inside MySQL database but I am getting an error message when executing the PHP command.

$json = json_decode($response); $json_feed = "data->value"; // i am pulling this data from my database foreach ($json->$json_feed as $elem) { // getting an conversion error in this line ..... } 
2
  • 1
    Error? Please ALWAYS show us ALL the error message and never a summaryCommentedMay 25, 2022 at 11:31
  • Variable access to object properties does not work across multiple->. You would be accessing a property that is literally named data->value with this.
    – C3roe
    CommentedMay 25, 2022 at 11:35

1 Answer 1

0

As @CBroe says "Variable access to object properties does not work across multiple ->"

If your data is predictable enough to know you can split the string and use the bits you could do

// just setting up your data structure here $json = new stdClass; $sub = new stdClass; $sub->value = [100, 200]; $json->data = $sub; $json_feed = "data->value"; $bits = explode('->', $json_feed); print_r($bits); print_r($json->{$bits[0]}->{$bits[1]}); 

The result of that test code is

Array ( [0] => 100 [1] => 200 ) 

So you can do

foreach ($json->{$bits[0]}->{$bits[1]} as $num){ echo $num.PHP_EOL; } 

Result would be

100 200 
3
  • That's extremely helpful. Thank you for your prompt reply. Will give it a go soon. Best.CommentedMay 25, 2022 at 14:57
  • The problem remains, I still have to insert the sign (->) manually for each value in the foreach loop. Is there any way to built the full array structure automatically in the the foreach statement including the -> sign?CommentedMay 25, 2022 at 15:06
  • as described in my sample code. The error is a standard PHP stdClass conversion error Array to StringCommentedMay 25, 2022 at 15:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.