0

我要做的是在用户名匹配的索引处替换 JSON 数组的值。我该怎么做呢?下面是我的试用 PHP 代码和我的 JSON。使用 array_replace 是最好的方法还是我应该以不同的方式去做?

<?php 
 $user_with_game = file_get_contents("oneuser.json");//$_POST["userGames"];
//$user_with_game = stripslashes ($JSON);
$user_decoded_JSON = json_decode($user_with_game, true);

$JSON = file_get_contents("users.json");
$decoded_JSON = json_decode($JSON, true);

//print_r ($user_decoded_JSON);

foreach ($decoded_JSON['Users'] as $key => $value)
{
    if ( $value['username'] == $user_decoded_JSON['username'])
    {
        $decoded_JSON['Users'] = array_replace($decoded_JSON['Users'],      $user_decoded_JSON);
    }
}

//print_r ($decoded_JSON);
$encoded_JSON = json_encode( $decoded_JSON);
echo $encoded_JSON;
 ?>



**users.json**
{
"Users":[
  {
     "password":"glass",
     "gamelist":[
        {
           "platform":"xbox-360",
           "game":"bioshock infinite"
        },
        {
           "platform":"xbox-360",
           "game":"tomb raider"
        }
     ],
     "username":"dorinayres",
     "reviewerlist":[

     ]
  },
  {
     "password":"happy",
     "gamelist":[
        {
           "platform":"xbox-360",
           "game":"far cry 3"
        },
        {
           "platform":"xbox-360",
           "game":"terraria"
        }
     ],
     "username":"ian",
     "reviewerlist":[

     ]
  }
  ]
}


**oneuser.json**
 {
"password":"glass",
 "gamelist":[
 {
     "platform":"xbox-360",
     "game":"bioshock infinite"
  },
  {
     "platform":"xbox-360",
     "game":"tomb raider"
  }
],
"username":"dorinayres",
"reviewerlist":[

]
}
4

2 回答 2

0

PHP foreach 并通过引用传递

foreach($decoded_JSON['Users'] as &$user){
    if($user['username'] == $user_decoded_JSON['username']){
        //do something directly on $user here and it will effect the actual array
    }
}
于 2013-05-16T17:44:05.493 回答
0
$decoded_JSON_tmp=$decoded_JSON;
foreach ($decoded_JSON['Users'] as $key => $value)
{
    if ( $value['username'] == $user_decoded_JSON['username'])
    {
        $decoded_JSON_tmp['Users'] = array_replace($decoded_JSON['Users'],      $user_decoded_JSON);
    }
}
$decoded_JSON=$decoded_JSON_tmp;
于 2013-05-16T17:47:15.130 回答