如何在php中替换数组中索引处的值


How do i go about replacing a value at a index in a array in php

我要做的是在用户名匹配的索引处替换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":[
]
}

PHP foreach and pass by reference

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