2010-08-20 28 views
0

現在我有通過更值替換陣列中的一個值,並保持其位置順序

$data = array("red", "green", "blue", "yellow"); 

$found = "green"; 
$expand1 = "apple"; 
$expand2 = "other"; 
if $data = array("red", "green", "blue", "yellow"); //[1]=>"green" 
I want get the new array look like this 
$result = array("red", "apple","other", "blue", "yellow"); 

if $data = array("green", "blue", "yellow","red");//[0]=>"green" beginning 
I want get the new array look like this 
$result = array("apple","other", "blue", "yellow","red"); 


if $data = array("blue", "yellow","red","green");//[3]=>"green" the end 
I want get the new array look like this 
$result = array("blue", "yellow","red","apple","other"); 

Anyboday知道sulotion.please。

感謝

回答

4

時退房PHP數組拼接功能

http://php.net/manual/en/function.array-splice.php

所以......

$result = array_splice($data,1,1,array("apple","other")); 

應該做的伎倆。

+0

在這種情況下,我們如何用「apple」,「other」來代替「綠色」,並保留訂單位置 – kn3l 2010-08-20 14:55:37

+0

$ pos = array_sear($ found,$ data); $ result = array_splice($ data,1,1,array(「apple」,「other」)); – kn3l 2010-08-20 15:13:09

+0

Right,$ pos = array_search(「green」,$ data); $ result = array_splice($ data,$ pos,1,array(「apple」,「other」));將用「apple」和「other」替換$ data數組中的「green」,分別在新的$ result數組中創建其索引1和2(並將其他索引推回)。 – clumsyfingers 2010-08-20 15:18:16

相關問題