2012-09-13 19 views
3

我在使用精确给定索引替换数组中的值时遇到问题。确切地说,我想用一个新的数字替换数组[2]中的字符串,但我没有一个想法。所以,请对我的资源一起来看看:用指定索引替换php数组中的值

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 

从上面,我想从“新”,所以预期的结果应该是一个新的字符串替换“成本”的字符串索引“0”:

6300-5200-4600-5600-4100 

我试图寻找无处不在,但没有什么回报,但array_search - 这不是我所期待的。请指教。

+0

安置自己的PHP代码 –

+0

怎么又是你数组看?你在这里没有什么PHP代码,但正常的,如果你有一个数组,你可以通过使用'$ array [$ index] = $ newvalue来访问/替换一个值'' –

回答

7
$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 
+0

+1优雅的解决方案 –

+0

@Mihai lorga 我试过你的代码,这似乎是最清晰的。但结果有点奇怪 - 价值增加了​​。它变成了六个阵列而不是五个。代码如下:代码 room_rate_updatez.php?rate | 502 | 6200-5200-4600-5600-4100 | 3 = 5500 foreach($ _ GET as $ key => $ _ val){ \t list($ _ name, $ _id,$ _成本,$ _ POS)=爆炸( “|”,$键); \t $ cost = explode(' - ',$ _val); // make it array \t $ cost [$ _ pos] = $ _cost; //用$ new更改仓位$ pos \t $ cost = implode(' - ',$ cost); // return new $ cost \t echo“new cost:”。$ cost; //新费用:5500-6200-5200-4600-5600-4100 }' – Wilf

+0

但是它应该是'$ cost = explode(' - ',$ _cost);' –

0

试试这个:

$the_array[$pos] = $new 
+0

@mike:为什么编辑我的答案? – JvdBerg

+1

添加语法颜色 - 但没有颜色出现... :) –

+0

你的意思是:$ cost [$ pos] = $ new ??? – Wilf

1

它是如此简单:

<?php 

$array = array(
    6200, 
    5200, 
    4600, 
    5600, 
    4100 
); 

$pos = 0; 
$new = 6300; 

$array[$pos] = $new; 

?> 
+0

@ hims056,你编辑的是什么?刚刚删除了2个新行!!!?重点? – Night2

+0

这是你的第一篇文章。所以它来到[测试评论 - 第一篇文章](http://stackoverflow.com/review/)。要审查它,我们必须编辑,投票,标记帖子。我发现你的文章没有错。所以只是编辑和检查它很好。 :) – hims056

+0

而不是旧的更新,您可以使用[回滚功能](http://meta.stackexchange.com/a/18876/187824)撤消编辑。 – hims056