我有一个简单的 json 文件。这是结构。
1 个玩家数组,其中包含 1 个游戏和 2 个匹配数组。
我想将数据添加到 matches[0]..first 匹配数组。
我正在使用 matchid 属性,该属性必须存储在适当的匹配数组中。
因此,如果我的 matchid 是 4..我希望我的数据存储在 match[0][4] 中。我尝试了各种组合,但无法得到我想要的。
这是我的 json 文件,后面是我尝试过的代码。
{
"players": [
{
"name": "Moldova",
"image": "/Images/Moldova.jpg",
"roll_over_image": "tank.jpg"
},
{
"name": "Georgia",
"image": "/Images/georgia.gif",
"roll_over_image": "tank.jpg"
},
{
"name": "Belarus",
"image": "/Images/Belarus.gif",
"roll_over_image": "tank.jpg"
},
{
"name": "Armenia",
"image": "/Images/armenia.png",
"roll_over_image": "tank.jpg"
},
{
"name": "Kazahstan",
"image": "/Images/kazahstan.gif",
"roll_over_image": "tank.jpg"
},
{
"name": "Russia",
"image": "/Images/russia.gif",
"roll_over_image": "tank.jpg"
},
{
"name": "Ukraine",
"image": "/Images/ukraine.png",
"roll_over_image": "tank.jpg"
},
{
"name": "Uzbekistan",
"image": "/Images/uzbekistan.gif",
"roll_over_image": "tank.jpg"
}
],
"games": [
{
"matches": [
{
"player1id": 0,
"player2id": 1,
"winner": "*"
},
{
"player1id": 2,
"player2id": 3,
"winner": "*"
},
{
"player1id": 4,
"player2id": 5,
"winner": "*"
},
{
"player1id": 6,
"player2id": 7,
"winner": "*"
},
{
"player1id": 0,
"player2id": 2,
"winner": "*"
},
{
"player1id": 4,
"player2id": 6,
"winner": "*"
},
{
"player1id": 0,
"player2id": 4,
"winner": 4
}
]
},
{
"matches": [
{
"player1id": 0,
"player2id": 1,
"winner": "*"
},
{
"player1id": 2,
"player2id": 3,
"winner": "*"
},
{
"player1id": 4,
"player2id": 5,
"winner": "*"
},
{
"player1id": 6,
"player2id": 7,
"winner": "*"
},
{
"player1id": 0,
"player2id": 2,
"winner": "*"
},
{
"player1id": 4,
"player2id": 6,
"winner": "*"
},
{
"player1id": 0,
"player2id": 4,
"winner": 0
}
]
}
]
和我试过的 php 代码。
$inp = file_get_contents('jsontrail.json');
$tempArray = json_decode($inp, true);
//adding to the matchid index of matches array
$matchid=3;
$arrne['winner'] ="winner";
$arrne['player1id'] ="player1id";
$arrne['player2id'] ="player2id";
array_push($tempArray->games[0]->matches[0]->[$matchid], $arrne );
$jsonData = json_encode($tempArray);
file_put_contents('jsontrail.json', $jsonData);
print_r( $inp);
解析错误:语法错误,意外的 '[',期待 T_STRING 或 T_VARIABLE 或 '{' 或 '$' 现在收到此错误..
代码2试试
$inp = file_get_contents('jsontrail.json');
$tempArray = json_decode($inp, true);
//adding to the matchid index of matches array
$matchid=3;
$arrne['games']['matches'][0][$matchid]['winner'] ="winner";
$arrne['games']['matches'][0][$matchid]['player1id'] ="player1id";
$arrne['games']['matches'][0][$matchid]['player2id'] ="player2id";
array_push($tempArray,$arrne );
$jsonData = json_encode($tempArray);
file_put_contents('jsontrail.json', $jsonData);
print_r( $inp);
但这将数组推到最后..