PHP按键替换多个数组的数组

时间:2017-09-22 11:08:38

标签: php arrays

  

我有Main Array,我想替换

Array
(
    [0] => {title-1}
    [1] => zebra
    [2] => {title-1}
    [3] => fruit
    [4] => {title-2}
    [5] => cars
    [6] => {title-3}
    [7] => city
    [8] => {title-3}
    [9] => amazing
    [10] => gold
    [11] => {title-2}
)

然后我有3个这样的数组

 Array
    (
        [0] => Blue
        [2] => Red
    )
    Array
    (
        [6] => lamborghini
        [8] => bugati

    )
   Array (

    [4] => Yellow
    [11] => dodge
)

我想像那样输出

    (
        [0] => blue
        [1] => zebra
        [2] => red
        [3] => fruit
        [4] => yellow
        [5] => cars
        [6] => lamborghini
        [7] => city
        [8] => bugati
        [9] => amazing
        [10] => gold
        [11] => dodge
    )

我尝试使用array_replace_recursive()但只能在一个数组中使用 可以任何身体帮助我

2 个答案:

答案 0 :(得分:0)

要使用array_replace_recursive,两个数组键应该相同。请参阅下面的代码。

$base = array('0' => '{title-1}', '1' => 'zebra','2'=>'{title-1}','3'=> 'fruit','4' => '{title-2}',5 => 'cars',6 => '{title-3}',7 => 'city');
$tem=array ( 0 => 'Blue', 2 => 'Red' ) ;

$tem1=array (4 => 'Yellow',6 => 'dodge');

$basket = array_replace_recursive($base, $tem);
$basket1 = array_replace($basket, $tem1);
print_r($basket1);

输出:

Array
(
    [0] => Blue
    [1] => zebra
    [2] => Red
    [3] => fruit
    [4] => Yellow
    [5] => cars
    [6] => dodge
    [7] => city
)

答案 1 :(得分:0)

如你所说,你有3个数组,它包含主数组的值。没有什么可以做的事情。

您只需使用" array-replace":

$arrayMain = array(0 => "{title-1}", 1 => "zebra", 2 => "{title-1}");
$arrayReplace = array(0 => "Blue", 2 => "Red");

$finishedArray = array_replace($arrayMain, $arrayReplace);

这会给你:

array(
    0 => "Blue",
    1 => "zebra",
    2 => "Red",
);

您实际上可以使用它来替换多个数组中的多个array_keys,例如array_replace($ mainArray,$ replaceArray1,$ replaceArray2);等等。

检查PHP文档: http://php.net/manual/en/function.array-replace.php