如何在PHP中添加具有新值的新键以存在数组?

时间:2018-08-08 21:49:28

标签: php json

我正在尝试通过键添加值以存在数组

这是我的数组

{
  "object": {
    "USER_ID": "1",
    "EMAIL": "abdabughazaleh@hotmail.com",
    "FIRST_NAME": "abd",
    "LAST_NAME": "abughazaleh",
    "PICTURE": "images/users/xuhEzR6m4LvjCuKx1vAb.jpg"
  }
}

具有json结果。

我需要添加这样的元素:

{
  "object": {
    "USER_ID": "1",
    "EMAIL": "abdabughazaleh@hotmail.com",
    "FIRST_NAME": "abd",
    "LAST_NAME": "abughazaleh",
    "PICTURE": "images/users/xuhEzR6m4LvjCuKx1vAb.jpg",
    "new_key": "new_value"
  }
}

当我尝试这个时:

 array_push($ar['object'],array('new_key'=>'new_value'));

这:

$ar['object']['new_key'] = 'new_value';

问题无法为我解决:(

2 个答案:

答案 0 :(得分:5)

这不是数组,这是json

{
  "object": {
    "USER_ID": "1",
    "EMAIL": "abdabughazaleh@hotmail.com",
    "FIRST_NAME": "abd",
    "LAST_NAME": "abughazaleh",
    "PICTURE": "images/users/xuhEzR6m4LvjCuKx1vAb.jpg"
  }
}

首先,使用json_decode将json转换为关联数组:

$json = '{
  "object": {
    "USER_ID": "1",
    "EMAIL": "abdabughazaleh@hotmail.com",
    "FIRST_NAME": "abd",
    "LAST_NAME": "abughazaleh",
    "PICTURE": "images/users/xuhEzR6m4LvjCuKx1vAb.jpg"
  }
}';

$json = json_decode($json, true); //true second parameter is actully for converting json into associative array

比向新创建的数组添加值:

$json['object']['key'] = 'value';

print_r($json)的结果:

Array
(
    [object] => Array
        (
            [USER_ID] => 1
            [EMAIL] => abdabughazaleh@hotmail.com
            [FIRST_NAME] => abd
            [LAST_NAME] => abughazaleh
            [PICTURE] => images/users/xuhEzR6m4LvjCuKx1vAb.jpg
            [key] => value
        )

)

然后转换回json:

$json = json_encode($json);

echo $json;的结果:

{
"object":{
        "USER_ID":"1",
        "EMAIL":"abdabughazaleh@hotmail.com",
        "FIRST_NAME":"abd",
        "LAST_NAME":"abughazaleh",
        "PICTURE":"images\/users\/xuhEzR6m4LvjCuKx1vAb.jpg",
        "key":"value"
    }
}

答案 1 :(得分:0)

我使用此代码解决了该问题,

  <?php   $array->object->new_key ='new_value'; ?>