PHP - 更新或创建多维数组

时间:2017-03-31 08:22:06

标签: php json

在我的代码中,我正在检查两个变量是否为false。如果两者都为假,那么我想用值更新名为responseArray的数组。如果两个变量都为false,我无法弄清楚如何更新数组两次而不覆盖该值。这用于捕获已注册的用户名和电子邮件地址。

以下是代码:

if($usernameAvailable == false)
    {
      /*Update validation error array that username taken*/
      if(isset($responseArray['ErrorArray']['Validation']))
      {
        /*Already another validation error exist in the array, add to it*/
        $utilitiesInstance->array_push_assoc($responseArray['ErrorArray']['Validation'], "Username", "Username Already Taken");
      }else{
        /*No array with validation errors is created...create it.*/
        $responseArray = array("ErrorArray"=>array("Validation"=>array("Username"=>"Username Already Taken")), "requestSuccessful"=>false);
      }
    }

    if($emailAvailable == false)
    {
      /*Update validation error array that Email already registered*/
      if(isset($responseArray['ErrorArray']['Validation']))
      {
        /*Already another validation error exist in the array, add to it*/
        $utilitiesInstance->array_push_assoc($responseArray['ErrorArray']['Validation'], "Email", "Email Already Registered");
      }else{
        /*No array with validation errors is created...create it.*/
        $responseArray = array("ErrorArray"=>array("Validation"=>array("Email"=>"Email Already Registered")), "requestSuccessful"=>false);
      }
    }

当我同时输入用户名和电子邮件时,我得到的是以下输出:

  

{" ErrorArray":{"验证":{"用户名":"用户名已经   采取"}}," requestSuccessful":假}

虽然它还应该在上面的验证数组中包含电子邮件项,因为它也是错误的。这正是我想要在这种情况下作为输出:

  

{" ErrorArray":{"验证":{"用户名":"用户名已经拍摄",   "电子邮件":"电子邮件已注册"}}," requestSuccessful":false}

以下是我用于函数array_push_assoc()的代码,以防万一:

function array_push_assoc($array, $key, $value){
    $array[$key] = $value;
    return $array;
  }

2 个答案:

答案 0 :(得分:0)

您的数组push方法返回传递给它的数组的副本,它对原始数组$responseArray没有影响。

要修复此更改您的方法以获取对数组的引用并进行更改:

function array_push_assoc_inplace(&$array, $key, $value)
{
    $array[$key] = $value;
}

但是,大多数代码似乎都是不必要的,您只需使用以下内容即可获得相同的结果:

if($usernameAvailable == false){
    $responseArray['ErrorArray']['Validation']['Username']='Username Already Taken';
}
if($emailAvailable == false){
    $responseArray['ErrorArray']['Validation']['Email']='Email Already Registered';
}

答案 1 :(得分:0)

试试这个伙伴:

if($usernameAvailable == false) {
    $responseArray['ErrorArray']['Validation'][] = array("Username"=>"Username Already Taken");
    $responseArray['ErrorArray']['requestSuccessful'] = false;
}

if($emailAvailable == false) {
    $responseArray['ErrorArray']['Validation'][] = array("Email"=>"Email Already Registered");
    $responseArray['ErrorArray']['requestSuccessful'] = false;
}