我试图遍历嵌套的JSON数据以查找具有特定字符串的名称,并提取与之关联的字符串值。在这种情况下,名称字符串是“myKey”,值字符串是“12345678”。
在查看了几个类似的问题和文档之后,我尝试了不同的方法,例如使用对象或关联数组,但最终仍然无法获取我想要的信息或收到错误。
错误类型:
make
以下是使用$ myObj = json_decode($ result)的解码JSON的片段;
Notice: Array to string conversion
Warning: Invalid argument supplied for foreach()
Trying to get property of non-object
以下是我尝试过的PHP代码片段:
object(stdClass)#4 (3) {
["info"]=>
object(stdClass)#5 (10) {
.
.
.
}
["stuff"]=>
array(1) {
.
.
.
}
["result"]=>
array(3) {
[0]=>
object(stdClass)#7 (3) {
["name"]=>
["value"]=>
["description"]=>
}
[1]=>
object(stdClass)#8 (2) {
["name"]=>
string(4) "Units"
["value"]=>
array(2) {
[0]=>
array(6) {
[0]=>
object(stdClass)#9 (3) {
.
.
.
}
.
.
.
[5]=>
object(stdClass)#14 (2) {
["name"]=>
string(10) "Components"
["value"]=>
array(1) {
[0]=>
array(14) {
[0]=>
object(stdClass)#15 (3) {
.
.
.
}
[1]=>
object(stdClass)#16 (3) {
["name"]=>
string(5) "myKey"
["value"]=>
string(8) "12345678"
["description"]=>
}
.
.
.
我可以直接访问我需要的内容:
$myObj = json_decode($result);
// or I have tried
// $myObj = json_decode($result, true);
// here are different snippets of code I tried
foreach($myObj->result as $test) {
echo '<pre>';
print_r($test->name);
echo "<br>";
if ($test->name == "Units") {
$resultName = $test->name;
echo $resultName . "<br>";
}
echo '</pre>';
}
/*
foreach($myObj->result as $test) {
echo $test . "<br>";
foreach($test->name as $test1) {
echo $test1 . "<br>";
foreach($test1->value as $test2) {
echo $test2 . "<br>";
}
}
}
*/
/*
foreach($myObj->result as $test) {
if (($test->name) == "Units") {
// grab the value that corresponds to the name
$units = $test->name;
if (($units->name) == "Components") {
$components = $units->name;
print_r($components);
}
}
}
*/
但值的位置可能会有所不同,所以我需要通过循环找到对象的名称
任何人都可以使用对象(甚至可能是关联数组)提供更好的方法吗?
print_r($myObj->result[1]->value[0][5]->value[0][1]->name);
print_r($myObj->result[1]->value[0][5]->value[0][1]->value);
答案 0 :(得分:1)
答案 1 :(得分:0)
以下是编码和解码的代码。希望这有助于你
//Encoding
//Array Values
$a1=array("name"=>"abc", "value"=>"def", "description"=>"ghi");
$a2=array("name"=>"jkl", "value"=>"mno", "description"=>"pqr");
$a3=array("name"=>"stu", "value"=>"wxy", "description"=>"zab");
//Array of Value Arrays
$info=array($a1, $a2, $a3);
$result=array($a1, $a2, $a3);
$stuff=array($a1, $a2, $a3);
//The Main Enclosed Array
$main=json_encode(array("info"=>$info, "result"=>$result, "stuff"=>$stuff));
//Decoding
//Fetching the name from result's $a1 array
$main_array=json_decode($main);
echo $main_array->result[1]->name; //Displays jkl