替换数组索引值

时间:2016-08-26 09:31:19

标签: php arrays

我有一个数组,其中存储了将发送到execute()的用户值; mysqli查询的函数。 所以,我希望替换索引值。

现在我在这里做的是使用str_replace();在foreach循环中这样做的功能,但问题是我将如何获得更新的数组?

$fields = array(
 'field_id' => '123', 
 'field_name' => 'test_name' 
);

foreach ($fields as $key => $field) {
  $val  = str_replace($key, $key, ':'.$key);
  $data = array();
  $data[$val] = $field;
} 

//I only got the value for the last index 1st is not there
print_r($data);

//output which I am expecting will be the following
$fields = array(
  ':field_id' => '123',
  ':field_name' => 'test_name'
);

如果有人能帮助我,请告诉我

1 个答案:

答案 0 :(得分:3)

  

目标是在每个键前加上冒​​号(:)。

     

这可以通过循环主阵列,修改每个来实现   在 $ newArray 中键入并填充这些键值对。

我们可以遍历 $ fields ,获取每个密钥并在其前面加上“:”,并将其作为 $ newArray 的关键字。即field_id变为:field_id,field_name变为:field_name ..等等。

这些值会从 $ fields 中复制并按原样放入 $ newArray

$newArray = array();
foreach ($fields as $key => $field) {
     $newArray[':'.$key] = $field;
}
相关问题