2012-09-13 23 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