试图在PHP中读取StdClass对象

时间:2016-10-26 18:14:11

标签: php arrays json

我解码了一个包含PHP中的键和值的JSON数组。 JSON看起来像(缩短以便于理解)

json_decode

在我Array ( [0] => stdClass Object ( [code] => 123 ) [1] => stdClass Object ( [identification] => Some item ) [2] => stdClass Object ( [price] => $20 ) ) 之后,它看起来像这样:

foreach ($jarray as $key) {
    echo 0->$key;
}

如何读取密钥和值?

我已经尝试过搜索SO了,并且已经尝试过这样的事情:

foreach ($jarray as $key => $value) {
    echo $key;
    echo $value;
}

会引发500(ISE)错误。

还试过这个:

code - 123
identification - Some item
price - $20
...

也会引发500错误。

我不知道如何做到这一点......

编辑:基本上,我只是希望通过整个事情进行迭代,并且每次都获得关键和值,如下所示:

var express = require('express')
var app = express();
var http = require('http').Server(app);
var path = require('path');

var port = process.env.port || 1337;    
app.use(express.static(__dirname + 'client'));    
app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname,'client', 'HTML1.html'));
});

http.listen(port, function () {
    console.log(`listning on ${port}`);
})

2 个答案:

答案 0 :(得分:1)

$json = '[{"code":"123"},{"identification":"Some item"},{"price":"$20"}]';
$jarray = json_decode($json, true);

foreach ($jarray as $value) {
    foreach ($value as $key => $val) {
        echo $key;
        echo $val;
    }
}

答案 1 :(得分:0)

I hope so it will reduce loop process confusion and simple to do this task. 


$text = '[{"code":"123"},{"identification":"Some item"},{"price":"$20"}]';
$array = json_decode($text);**strong text**
foreach($array as $value)
{
    $array = (array)$value;
    $x = each($array);
    echo $x['key'];
    echo "====>>>>";
    echo $x['value'];
    echo "<br/>";
}