Unable to get dynamic PHP's Object value using PHP variable - php

PHP is unable to get the value for dynamic object prepared as:
$abc->{$dynamic_object_pattern}
Where the value of the variable $dynamic_object_pattern is, json->{'data_1'}->{'value'}
For me, PHP 7.1 is understanding the statically defined pattern like below, and fetching the value as it should:
$abc->json->{'data_1'}->{'value'}
But not when I put the whole portion into a variable and then try to get its value. I Tried,
$abc->{$dynamic_object_pattern} and $abc->$dynamic_object_pattern
both ways, but no solution yet.
The error comes is Notice: Undefined property: stdClass::$json->{'data_1'}->{'value'}

I'm attempting an answer without seeing your JSON data
Here you say :
But not when I put the whole portion into a variable and then try to
get its value
From that line alone it sounds like you are trying to get value from a string rather than array. If you put the whole portion into a variable, PHP will interpret it as string. Make sure you add array() before newly created variable.
Natural array :
$array = array();
Now a string
$variable = $array;
Convert string to array
$new_array = array($variable);
Also, have you tried decoding?
// decode
$response = json_decode($new_array, true);
//print out
var_export(array_unique(array($response)));

Related

PHP - get first value from array with single line using native functions

I have a function asdf() that returns an array ["key" => "value"]. I would like to print out value with one line, but reset() function suggested in similar questions does not work for me because reset only takes variable as a argument and doesent accept function. So if i try reset(asdf()) i get an exception: "Only variables should be passed by reference".
So my question is how can i print "value" from asdf() in a single line only using php native functions.
Actually reset function used to move the array's internal pointer to the first element, I think you must use current function that is return the current element in an array
Try like this
print current(asdf());
Try this:
current(array_values(asdf()));
It uses current to avoid the pass by reference error and array_values to ensure the array passed to current has the first element as it's current element.
Though unless you have a very good reason assigning the array to a variable and then using reset would be better.

Retrieve value from array

While retrieving values from array without index in PHP I am getting nothing.
From my database value is stored like ["SCHOOL"] and I want to get just SCHOOL from this.
It's not treated as array instead it's treated as a string.
What will be the solution if want to treat this as array and get value of that array.
My Code is as follows :
$stream_arr = $res_tbl['streams'];
which gives result as ["SCHOOL"]
and I want just SCHOOL from this.
I am using code as $stream = $stream_arr[0];
and I get '[' this as result.
If I assign manual value to $stream_arr = ["SCHOOL"],
above code works and returns SCHOOL as expected.
But for results from my database is not working where result is same as the one I manually assigned.
To eliminate braces from the string you can use below code.
$stream_arr = '["SCHOOL"]';
$temp=explode('"',$stream_arr);
$val=$temp[1];
echo $val; //it will dispaly 'SCHOOL'.
But check the insert query(from the place you store data into db) that why it is storing with braces? if it is done by you as required then proceed else first fix that issue instead of eliminating braces in php code.

php: accessing array dynamically using a string variable

Its like this
I have a variable that has an array index in it, for e.g.
$var = 'testVar["abc"][0]';
or
$var = 'testVar["xyz"][0]["abc"]';
or it could be anything at run time.
Now when I try to access this by using this php code:
echo $$var;
or
echo ${$var};
I get a warning saying Illegal offset at line ...
but if I use this code, it works
eval('echo $'.$var);
I do not want to use eval(). Is there any other way?
EDIT:
The variable $testVar is an array build up on runtime and it could have multi-dimensional array built dynamically. Its format is not fixed and only the script knows by the use of certain variables that what the array could be.
for e.g. at any point, the array might have an index $["xyz"][0]["abc"] which I want to access dynamically.
My php version is 5.1
According to the documentation, what you are trying to accomplish is not possible:
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
In your case, $$var tries to read a variable with the name testVar["xyz"][0]["abc"], and not indexing an array. You could dereference that array like this:
$a = "testVar";
echo ${$a}["xyz"][0]["abc"];

Convert key-value JSON to object and refer individual values directly

I am making a web app. In one part of it, I have JS send a string(in json format) to PHP.
The value php receives is:
{"date":"24-03-2014","Cars":["Cheap","Expensive"]}
Now, this is saved in a variable $meta. The problem I am facing is, as to how do I convert this string into an object and reference each individual entry separately.
I have tried json_decode and json_encode
and then I have referenced each variable using $meta.["date"] and $meta.date but nothing seams to work. I am getting just { as the output.
What's the correct way to do this?
$str = '{"date":"24-03-2014","Cars":["Cheap","Expensive"]}';
$obj = json_decode($str);
echo $obj->date;
// 24-03-2014
Usually a $my_obj = json_decode($_POST['jsonstring'], 1); (true supply means it'll be returned as an assoviative array) should be the way to go. If I were you I'd probably try a var_dump($my_obj); to see what actually comes through. If it doesn't work you'll want to make sure that you correctly submit a valid json string, e.g. JSON.stringify();
You should check out the PHP doc page for json_decode here.
By default, unless you pass true as the second parameter for json_decode, the function call will return an object, which you can access the members of by using:
$meta->date
The arrow operator will allow you to access object values, not the square brackets or a dot.

Variable in $_POST returns as string instead of array

In my form i have fields with name photoid[] so that when sent they will automatically be in an array when php accesses them.
The script has been working fine for quite some time until a couple days ago. And as far as i can remember i havent changed any php settings in the ini file and havent changed the script at all.
when i try to retrieve the array using $_POST['photoid'] it returns a string with the contents 'ARRAY', but if i access it using $_REQUEST['photoid'] it returns it correctly as an array. Is there some php setting that would make this occur? As i said i dont remember changing any php settings lately to cause this but i might be mistaken, or is there something else i am missing.
I had the same problem. When I should recieve array via $_POST, but var_dump sad: 'string(5) "Array"'. I found this happens, when you try use trim() on that array!
Double check your code, be sure you're not doing anything else with $_POST!
Raise your error_reporting level to find any potential source. It's most likely that you are just using it wrong in your code. But it's also possible that your $_POST array was mangled, but $_REQUEST left untouched.
// for example an escaping feature like this might bork it
$_POST = array_map("htmlentities", $_POST);
// your case looks like "strtoupper" even
To determine if your $_POST array really just contains a string where you expected an array, execute following at the beginning of your script:
var_dump($_POST);
And following for a comparison:
var_dump(array_diff($_REQUEST, $_POST));
Then verifiy that you are really using foreach on both arrays:
foreach ($_POST["photoid"] as $id) { print $id; }
If you use an array in a string context then you'll get "Array". Use it in an array context instead.
$arr = Array('foo', 42);
echo $arr."\n";
echo $arr[0]."\n";
​
Array
foo
$_POST['photoid'] is still an array. Just assign it to a variable, and then treat it like an array. ie: $array = $_POST['photoid'];
echo $array[0];

Categories