我有以下json文件。
{
"posts": [{
"by": "johir",
"post": "Hello Ajax took",
"likes": 0
}, {
"by": "johir",
"post": "Now Work",
"likes": 0
}, {
"by": "johir",
"post": "Now Work",
"likes": 0
}, {
"by": "johir",
"post": "Here we go",
"likes": 0
}, {
"by": "johir",
"post": "Truely painful",
"likes": 0
}, {
"by": "johir",
"post": "Hello Ajax 4",
"likes": 0
}, {
"by": "johir",
"post": "Hello Ajax 2",
"likes": 0
}, {
"by": "johir",
"post": "Hello Ajax",
"likes": 0
}]
}
我想从这个json文件中访问帖子。我编写了以下代码来访问特定帖子并将其更改为其他值:
$inp = file_get_contents('posts.json');
$tempArray = json_decode($inp);
error_log($post);
$tempArray=$tempArray->posts;
$tempArray[2]['post']=" Done";
但它不起作用。有没有替代方法呢?我已经尝试了很多来解决这个问题,但我很困惑为什么这不起作用?
答案 0 :(得分:1)
<?php
$sInFile = 'in.json';
$sRaw = file_get_contents( $sInFile );
$aInData = json_decode( $sRaw );
$aPosts = $aInData->posts;
$iCountData = count( $aPosts );
for( $i = 0; $i < $iCountData; ++$i )
{
var_dump( $aPosts[ $i ][ 'by' ] );
var_dump( $aPosts[ $i ][ 'post' ] );
var_dump( $aPosts[ $i ][ 'likes' ] );
}
?>
答案 1 :(得分:1)
当你处理json字符串时,理解如何遍历它的简单方法是执行json_decode()然后转储结果,这样你就可以看到你正在处理的内容,如果你不读原始的JSON数据非常好。
这样做
$inp = '{
"posts": [{
"by": "johir",
"post": "Hello Ajax took",
"likes": 0
}, {
"by": "johir",
"post": "Now Work",
"likes": 0
}, {
"by": "johir",
"post": "Now Work",
"likes": 0
}, {
"by": "johir",
"post": "Here we go",
"likes": 0
}, {
"by": "johir",
"post": "Truely painful",
"likes": 0
}, {
"by": "johir",
"post": "Hello Ajax 4",
"likes": 0
}, {
"by": "johir",
"post": "Hello Ajax 2",
"likes": 0
}, {
"by": "johir",
"post": "Hello Ajax",
"likes": 0
}]
}';
$tempArray = json_decode($inp);
print_r($tempArray);
这将输出此
stdClass Object
(
[posts] => Array
(
[0] => stdClass Object
(
[by] => johir
[post] => Hello Ajax took
[likes] => 0
)
[1] => stdClass Object
(
[by] => johir
[post] => Now Work
[likes] => 0
)
[2] => stdClass Object
(
[by] => johir
[post] => Now Work
[likes] => 0
)
[3] => stdClass Object
(
[by] => johir
[post] => Here we go
[likes] => 0
)
[4] => stdClass Object
(
[by] => johir
[post] => Truely painful
[likes] => 0
)
[5] => stdClass Object
(
[by] => johir
[post] => Hello Ajax 4
[likes] => 0
)
[6] => stdClass Object
(
[by] => johir
[post] => Hello Ajax 2
[likes] => 0
)
[7] => stdClass Object
(
[by] => johir
[post] => Hello Ajax
[likes] => 0
)
)
)
所以现在你知道json_decode创建了一个带有一个名为posts
的属性的对象,它是一个数组。该数组是其他对象的数组。每个对象都有3个属性,by
和post
以及likes
。
所以现在我们看到$tempArray
不是一个非常有用的变量名,所以也许我们应该这样编码:
$inp = file_get_contents('posts.json');
$tempObj = json_decode($inp);
因此,您现在可以对此进行处理以获取所有post
值,如下所示:
foreach ( $tempObj->posts as $post ) {
echo $post->post;
}
或者按照这样的特定值:
echo $tempObj->posts[2]->post;
或设置其中一个值
$tempObj->posts[2]->post = ' Done';