数组:用其他预定义值替换元素


Array: replace the element with other predefined values

我有一个数组sayarray1(asd,ard,f_name,l_name)现在我想替换一些值作为

协议开始日期为的asd

带名字的f_name。

带姓氏的l_name。

我所做的是这样的,但它不是检查第二个如果条件

  for($i = 0; $i < count($changedvalue);$i++){
  //Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to some value
if ($changedvalue[$i] == 'asd')
   {$changedvalue[$i] = 'Agreement Start Date';}
   elseif ($changedvalue[$i] == 'ard')
   {$changedvalue[$i] == 'Agreement Renewal Date';}
 }

你可以这样做:

foreach ($changedvalue as $key => $value)
{
     switch ($value)
     {
            case('asd'):
                $changedvalue[$key]='Agreement Start Date';
                break;
            case('f_name'):
                $changedvalue[$key]='first name';
                break;
            case('l_name'):
                $changedvalue[$key]='last name';
                break;
     }
}

通过这种方式,您可以遍历数组中的每一行,如果旧值等于其中一个重置值,则将该值设置为新值。

您在上一条语句中有一个拼写错误。'==='应该是赋值运算符'='

当前代码的问题是最后一行的==应该是=

然而,我建议将您的代码更改为这样的代码:

$valuemap = array(
   'asd' => 'Agreement Start Date',
   'f_name' => 'first name', 
    // and so on...
);
function apply_valuemap($input) {
    global $valuemap;
    return $valuemap[$input];
}
array_map('apply_valuemap', $changedvalue);

这样,添加更多要替换的值会更容易。