具有动态值的数组中的Echo元素

时间:2016-03-28 02:33:40

标签: php arrays decode

{  
"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"因为它旁边有动态值吗?我尝试使用

  

$ var1 = $ obj-> something5 [0] - > NeedToEchoThis;

但是......仍然无法奏效。有任何想法吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这实际上取决于你如何使用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";        
    }
}

答案 2 :(得分:0)

当你提到动态价值时,它并不是很清楚你的意思。你的json示例中的符号也不清楚。

如果&#34; 1232&#34;值更改,您可以按如下方式获取元素的动态值:

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";
}