php array replace recursive

PHP array_replace_recursive() Function

Example

Replace the values of the first array with the values from the second array recursively:

Definition and Usage

The array_replace_recursive() function replaces the values of the first array with the values from following arrays recursively.

Tip: You can assign one array to the function, or as many as you like.

If a key from array1 exists in array2, values from array1 will be replaced by the values from array2. If the key only exists in array1, it will be left as it is. If a key exist in array2 and not in array1, it will be created in array1. If multiple arrays are used, values from later arrays will overwrite the previous ones.

Note: If you do not specify a key for each array, this function will behave exactly the same as the array_replace() function.

Syntax

Parameter Values

ParameterDescription
array1Required. Specifies an array
array2Optional. Specifies an array which will replace the values of array1
array3.Optional. Specifies more arrays to replace the values of array1 and array2, etc. Values from later arrays will overwrite the previous ones.

Technical Details

Return Value:Returns the replaced array, or NULL if an error occurs
PHP Version:5.3.0+

More Examples

Example

Example

Differences between array_replace() and array_replace_recursive():

Источник

array_replace_recursive

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

array_replace_recursive — Рекурсивно заменяет элементы первого массива элементами переданных массивов

Описание

array_replace_recursive() заменяет значения массива array на соответствующие по ключам значения из всех следующих массивов. Если ключ из первого массива есть во втором, его значение будет заменено на значение из второго массива. Если ключ есть во втором массиве, но отсутствует в первом, он будет создан в первом массиве. Если ключ есть только в первом массиве, то он остаётся как есть. Если передано несколько массивов, они будут обработаны по порядку, последующие перезаписывают предыдущие значения.

Список параметров

Массив, элементы которого будут заменены.

Массивы, из которых будут браться элементы для замены.

Возвращаемые значения

Примеры

Пример #1 Пример использования array_replace_recursive()

Результат выполнения данного примера:

Пример #2 array_replace_recursive() и рекурсивное поведение

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 7 notes

(I suppose it treats it as just another recursive level to dive in, finding no key to compare, backtracking while leaving this sub-tree alone)

$result is still: [‘first’ => [‘second’ => ‘hello’]].

Nice that this function finally found its was to the PHP core! If you want to use it also with older PHP versions before 5.3.0, you can define it this way:

If you implemented such a compatible function before and don’t want to refactor all your code, you can update it with the following snippet to use the native (and hopefully faster) implementation of PHP 5.3.0, if available. Just start your function with these lines:

Источник

array_replace

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

array_replace — Replaces elements from passed arrays into the first array

Description

array_replace() replaces the values of array with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values.

array_replace() is not recursive : it will replace values in the first array by whatever type is in the second array.

Parameters

The array in which elements are replaced.

Arrays from which elements will be extracted. Values from later arrays overwrite the previous values.

Return Values

Examples

Example #1 array_replace() example

The above example will output:

See Also

User Contributed Notes 14 notes

// we wanted the output of only selected array_keys from a big array from a csv-table
// with different order of keys, with optional suppressing of empty or unused values

Here is a simple array_replace_keys function:

print_r(array_replace_keys([‘one’=>’apple’, ‘two’=>’orange’], [‘one’=>’ett’, ‘two’=>’tvo’]);
// Output
array(
‘ett’=>’apple’,
‘tvo’=>’orange’
)

Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.

To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:

array(3) <
«id» => NULL
«login» => string(8) «john.doe»
«credit» => int(100)
>

I would like to add to my previous note about my polecat_array_replace function that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

$array1 = array( «berries» => array( «strawberry» => array( «color» => «red», «food» => «desserts»), «dewberry» = array( «color» => «dark violet», «food» => «pies»), );

$array2 = array( «food» => «wine»);

This is will replace the value for «food» for «dewberry» with «wine».

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I’ve gained from this site.

I got hit with a noob mistake. 🙂

When the function was called more than once, it threw a function redeclare error of course. The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision. A simple logical step was all that was needed.

With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own. Since this site has helped me so much, I felt the need to return the favor. 🙂

$array2 = array( «food» => «wine» );

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I’ve gained from this site.

In some cases you might have a structured array from the database and one
of its nodes goes like this;

# string to transform
$string = «

name: %s, json: %s, title: %s

?>

I hope that this will save someone’s time.

Источник

PHP Функция array_replace_recursive()

Пример

Рекурсивно замените значения первого массива значениями из второго массива:

Определение и использование

Функция array_replace_recursive() рекурсивно заменяет значения первого массива значениями из следующих массивов.

Совет: Вы можете назначить функции один массив или столько, сколько захотите.

Если ключ из array1 существует в array2, значения из array1 будут заменены значениями из array2. Если ключ существует только в array1, он останется таким, как есть. Если ключ существует в array2, а не в array1, он будет создан в array1. Если используется несколько массивов, значения из более поздних массивов будут перезаписывать предыдущие.

Примечание: Если вы не зададите ключ для каждого массива, функция будет вести себя точно так же, как функция array_replace().

Синтаксис

Параметр значений

ПараметрОписание
array1Требуемый. Задает массив
array2Необязательный. Задает массив, который заменит значения array1
array3.Необязательный. Задает дополнительные массивы для замены значений array1 и array2, и т.д. Значения из более поздних массивов будут перезаписывать предыдущие.

Технические подробности

Возврат значения:Возвращает замененный массив или NULL, если возникает ошибка
PHP Версия:5.2.0+

Еще примеры

Пример

Пример

Различия между array_replace() и array_replace_recursive():

Источник

array_replace_recursive

array_replace_recursive — Рекурсивно заменяет элементы первого массива элементами переданных массивов

Описание

array_replace_recursive() заменяет значения первого массива array на соответствующие по ключам значения из всех следующих массивов. Если ключ из первого массива есть во втором, его значение будет заменено на значение из второго массива. Если ключ есть во втором массиве, но отсутствует в первом, он будет создан в первом массиве. Если ключ есть только в первом массиве, то он остается как есть. Если передано несколько массивов, они будут обработаны по порядку, последующие перезаписывают предыдущие значения.

Список параметров

Массив, элементы которого будут заменены.

Массив, из которого будут взяты элементы для замены.

Дополнительные массивы, из которых будут браться элементы для замены.

Возвращаемые значения

Примеры

Пример #1 Пример использования array_replace_recursive()

Результат выполнения данного примера:

Пример #2 array_replace_recursive() and recursive behavior

Результат выполнения данного примера:

Смотрите также

Коментарии

This might help out people who don’t have 5.3 running:

// Joins two or more arrays together recursively; key/value pairs of the first
// array are replaced with key/value pairs from the subsequent arrays. Any
// key/value pair not present in the first array is added to the final array
function array_join ()
<
// Get array arguments
$arrays = func_get_args ();

Nice that this function finally found its was to the PHP core! If you want to use it also with older PHP versions before 5.3.0, you can define it this way:

If you implemented such a compatible function before and don’t want to refactor all your code, you can update it with the following snippet to use the native (and hopefully faster) implementation of PHP 5.3.0, if available. Just start your function with these lines:

This is a fairly concise version which does not rely on traditional recursion:

If you came here looking for a function to recursively find and replace (scalar) values in an array (also recurses through objects):

(I suppose it treats it as just another recursive level to dive in, finding no key to compare, backtracking while leaving this sub-tree alone)

$result is still: [‘first’ => [‘second’ => ‘hello’]].

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *