php - 用给定的索引替换 php 数组中的值

标签 php arrays replace

我在用确切的给定索引替换数组中的值时遇到问题。确切地说,我想用一个新数字替换 array[2] 中的一个字符串,但我不知道。所以请查看我的资源:

pos:0 //position of index in array 
id:498 //id of a field
new:6300 //new value to replace in an array
cost:6200-5200-4600-5600-4100 //the array

从上面,我想用“new”中的新字符串替换“cost”中的字符串索引“0”,因此预期结果应该是:

6300-5200-4600-5600-4100

我试图到处搜索,但除了 array_search 没有返回任何东西——这不是我要找的。请指教。

最佳答案

$pos = 0;                            // position
$new = 6300;                         // new value
$cost = '6200-5200-4600-5600-4100';  // string
$cost = explode('-', $cost);         // make it array
$cost[$pos] = $new;                  // change the position $pos with $new
$cost = implode('-', $cost);         // return new $cost
// 6300-5200-4600-5600-4100

关于php - 用给定的索引替换 php 数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12402416/

相关文章:

java - 从 double 值和 boolean 值数组中删除一个元素

java - 为什么我只能引用传递给 onClickListener 的 TextView 数组中的最后一个元素

linux - 使用 sed 替换多个单词

vbscript - 替换所有空格

javascript - 将字符串数组转换为 csv 格式

PHPExcel 下载无法正常工作

php - 在 OmniPay 中获取 PayPal Rest 错误

php - 将多个数组中的数据插入到mysql数据库中的各个字段中

javascript - 'array[array.length - 1] = array.pop()' 会产生未定义的行为吗?

php - 使用 jQuery Ajax 获取单独的 PHP 变量