代码之家  ›  专栏  ›  技术社区  ›  Abd Abughazaleh

如何在PHP中为新数组添加新值?

  •  0
  • Abd Abughazaleh  · 技术社区  · 6 年前

    我试图用存在数组的关键字添加值

    这是我的阵列

    {
      "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 回复  |  直到 6 年前
        1
  •  5
  •   Tarasovych    6 年前

    这不是数组,这是 json :

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

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

    $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"
        }
    }
    
        2
  •  0
  •   Abd Abughazaleh    6 年前

    我用这个代码解决它,

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