简体   繁体   English

获取 stdClass 对象值

[英]Get stdClass Object value

I'm trying to get a value from stdClass Object array with no success.我试图从stdClass对象数组中获取一个值,但没有成功。

Here is the code I'm running:这是我正在运行的代码:

 $myjson =
 '{"2":{"label":"","value":"","type":null,"validation":null,"required":null},
 "6":{"label":"files","value":"getThisValue","type":"file0","validation":null,"required":null},
 "3":{"label":"location","value":"val3","type":"hidden","validation":"","required":"0"}
 ,"0":{"custom3":"zz","value":"","label":""},"1":{"custom3":"zz","value":"","label":""}
 }';

$json = json_decode($myjson);

echo $json[6]->'value';

This is doesn't work, If I Print_r the JSON after decoding (print_r($json)) , the array will look like this:这是行不通的,如果我在解码后Print_r JSON (print_r($json)) ,则数组将如下所示:

stdClass Object ( 
    [2] => stdClass Object ( [label] => [value] =>
[type] => [validation] => [required] => ) 
    [6] => stdClass Object (
[label] => files [value] => getThisValue [type] => file0 [validation]
=> [required] => ) 
    [3] => stdClass Object ( [label] => location [value] => val3 [type] => hidden [validation] => [required] => 0 ) 
    [0]
=> stdClass Object ( [custom3] => zz [value] => [label] => ) 
    [1] => stdClass Object ( [custom3] => zz [value] => [label] => ) )

I need the Value: getThisValue .我需要值: getThisValue Any idea how I can get it?知道我怎么能得到它吗? (I tried many options with no success). (我尝试了很多选择都没有成功)。

Try echo $json["6"]["value"];试试echo $json["6"]["value"]; But for this you have to use json_decode($myjson, true);但为此你必须使用json_decode($myjson, true); true, to get an array.真,得到一个数组。

Because it's going to be two arrays inside each other and not an object you have to use 2 brackets.因为它将是彼此内部的两个数组,而不是一个对象,所以您必须使用 2 个括号。

You could add true to your json_decode , like this: json_decode($myjson, true);您可以将true添加到您的json_decode ,如下所示: json_decode($myjson, true); , it will now convert your json object to an associative array. ,它现在会将您的 json 对象转换为关联数组。

And from there on you can get to the value you want by requesting the key, just like other arrays.从那里开始,您可以通过请求键来获得所需的值,就像其他数组一样。

$newArray = json_decode($myjson, true);
echo $newArray['something'];

You can't use a std object as an array.您不能将 std 对象用作数组。 But in order to get your code working just add this line:但是为了让您的代码正常工作,只需添加以下行:

$json = get_object_vars($json);

After this you can access it like this:在此之后,您可以像这样访问它:

echo $json[6]->value;

If you want to get the values from stdObject without converting it to array, you can do it like this:如果您想从 stdObject 获取值而不将其转换为数组,您可以这样做:

echo $json->{'6'}->value

You can use the {'property_name'} notation to get a value of a class property with non-standard name (for ex. a number).您可以使用{'property_name'}符号来获取具有非标准名称(例如数字)的类属性的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM