数组中具有动态值的回显元素


Echo element from array with dynamic value

{  
"something":"not important;",
"something2":"less important",
"something3":"inexistent",
"something4":"nothing",
"something5":{  
        "1232":{  // this value is dynamic
        "NeedToEchoThis":1230,
        "NeedToEchoThis2":"12343",
        "NeedToEchoThis3":22222,
  }
},
  "something6":"else",
"something7":"0"
}

使用 json_decode 时,我得到那个数组。但。。。如何回显"something5"中的值,因为它旁边有一个动态值?我试过使用

$var 1 = $obj->某物5[0]->需要回声;

但。。。仍然不起作用。有什么想法吗?

例如,

您可以使用foreach循环迭代数组something5

<?php
$data = json_decode(data(), true);
foreach( $data['something5'] as $k=>$v) {
    if ( isset($v['NeedToEchoThis']) ) {
        echo $k, ' -> NeedToEchoThis => ', $v['NeedToEchoThis'], "'r'n";
    }
}

function data() {
    return <<< eoj
{
    "something": "not important;",
    "something2": "less important",
    "something3": "inexistent",
    "something4": "nothing",
    "something5": {
        "1232": {
            "NeedToEchoThis": "1230",
            "NeedToEchoThis2": "12343",
            "NeedToEchoThis3": "22222"
        }
    },
    "something6": "else",
    "something7": "0"
}
eoj;
}

指纹

1232 -> NeedToEchoThis => 1230

当你提到动态值时,你的意思并不很清楚。json 示例中的表示法也不清楚。

如果"1232"值发生变化,您可以获得元素的动态值,如下所示:

if( !empty($obj->something5) ) { 
    $arr = (array) $obj->something5[0];
    if( is_array($arr) && !empty($arr) ) {
        $key = array_keys( $arr )[0];
        $var1 = $obj->something5[0]->{$key}->NeedToEchoThis;
    } else {
        $var1 = "nothing to show";
    }
} else { 
    $var1 = "nothing to show";
}

实际上取决于您如何使用json_decode。

当您json_decode($input(时,您将获得一个包含其他对象的对象(不是数组(。

$obj = json_decode($input);
echo $obj->something5->{'1232'}->NeedToEchoThis;

或:

$obj = json_decode($input, true);
echo $obj['something5'][1232]['NeedToEchoThis'];

下面是一个完整的可运行示例:

$input = <<<EEE
{  
"something":"not important;",
"something2":"less important",
"something3":"inexistent",
"something4":"nothing",
"something5":{  
    "1232":{  
        "NeedToEchoThis":1230,
        "NeedToEchoThis2":"12343",
        "NeedToEchoThis3":22222
    }
},
  "something6":"else",
  "something7":"0"
}
EEE;
echo $input . "'n";
$obj = json_decode($input);
var_dump($obj);
echo $obj->something5->{'1232'}->NeedToEchoThis;
echo "'n";
// If you don't know the key names:
$vars = get_object_vars ( $obj );
foreach($vars as $name => $value ) {
    if ( is_object($value) ) {
        echo "$name => "; print_r($value);
    } elseif( is_string($value) ){
        echo "$name => $value'n";        
    }
}