首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在php中替换数组中索引处的值?

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

Stack Overflow用户
提问于 2013-05-17 01:35:03
回答 2查看 63关注 0票数 0

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

代码语言:javascript
运行
复制
<?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":[

]
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-17 01:44:05

PHP foreach and pass by reference

代码语言:javascript
运行
复制
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
    }
}
票数 0
EN

Stack Overflow用户

发布于 2013-05-17 01:47:15

代码语言:javascript
运行
复制
$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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16593893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档