PHP.mk документација

array_replace

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.array-replace.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.array-replace.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
array_replace

Референца за `function.array-replace.php` со подобрена типографија и навигација.

function.array-replace.php

array_replace

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

array_replaceГи заменува елементите од дадените низи во првата низа

= NULL

array_replace(array $array, array ...$replacements): array

array_replace() креира нова низа и доделува ставки во неа за секој клуч во секоја од дадените низи. Ако клучот се појави во повеќе влезни низи, ќе се користи вредноста од најдесната влезни низа.

array_replace() не обработува елементи ставки рекурзивно, ја заменува целата вредност за секој клуч кога врши замена.

Параметри

array

Низата во која се заменуваат елементите.

replacements

Низи од кои ќе се извлечат елементи. Вредностите од подоцнежните низи ги презапишуваат претходните вредности.

Вратени вредности

Враќа array.

Примери

Пример #1 array_replace() example

<?php
$base
= array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
var_dump($basket);
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

array(5) {
  [0]=>
  string(5) "grape"
  [1]=>
  string(6) "banana"
  [2]=>
  string(5) "apple"
  [3]=>
  string(9) "raspberry"
  [4]=>
  string(6) "cherry"
}

Пример #2 Пример како се ракува со вгнездени низи

<?php
$base
= [ 'citrus' => [ 'orange', 'lemon' ], 'pome' => [ 'apple' ] ];
$replacements = [ 'citrus' => [ 'grapefruit' ] ];
$replacements2 = [ 'citrus' => [ 'kumquat', 'citron' ], 'pome' => [ 'loquat' ] ];

$basket = array_replace($base, $replacements, $replacements2);
var_dump($basket);
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

array(2) {
  ["citrus"]=>
  array(2) {
    [0]=>
    string(7) "kumquat"
    [1]=>
    string(6) "citron"
  }
  ["pome"]=>
  array(1) {
    [0]=>
    string(6) "loquat"
  }
}

Види Исто така

  • array_replace_recursive() - Ги заменува елементите од дадените низи во првата низа рекурзивно
  • array_merge() - Спој една или повеќе низи

Белешки од корисници — Интерпретира стринг од XML во објект

steelpandrummer
пред 13 години
<?php
// 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

$values = array
(
    'Article'=>'24497',
    'Type'=>'LED',
    'Socket'=>'E27',
    'Dimmable'=>'',
    'Wattage'=>'10W'
);

$keys = array_fill_keys(array('Article','Wattage','Dimmable','Type','Foobar'), ''); // wanted array with empty value

$allkeys = array_replace($keys, array_intersect_key($values, $keys));    // replace only the wanted keys

$notempty = array_filter($allkeys, 'strlen'); // strlen used as the callback-function with 0==false

print '<pre>';
print_r($allkeys);
print_r($notempty);

/*
Array
(
    [Article] => 24497
    [Wattage] => 10W
    [Dimmable] => 
    [Type] => LED
    [Foobar] => 
)
Array
(
    [Article] => 24497
    [Wattage] => 10W
    [Type] => LED
)
*/
?>
marvin_elia на web точка de
12 години пред
Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.
 
/**
  * @param array $array
  * @param array $replacements
  * @param boolean $override
  * @return array
  */
function array_replace_keys(array $array, array $replacements, $override = false) {
    foreach ($replacements as $old => $new) {
        if(is_int($new) || is_string($new)){
            if(array_key_exists($old, $array)){
                if(array_key_exists($new, $array) && $override === false){
                    continue;
                }
                $array[$new] = $array[$old];
                unset($array[$old]);
            }
        }
    }
    return $array;
}
ali dot sweden19 at yahoo dot com
пред 10 години
Here is a simple array_replace_keys function:

/**
     * This function replaces the keys of an associate array by those supplied in the keys array
     *
     * @param $array target associative array in which the keys are intended to be replaced
     * @param $keys associate array where search key => replace by key, for replacing respective keys
     * @return  array with replaced keys
     */
    private function array_replace_keys($array, $keys)
    {
        foreach ($keys as $search => $replace) {
            if ( isset($array[$search])) {
                $array[$replace] = $array[$search];
                unset($array[$search]);
            }
        }

        return $array;
    }

// Test Drive

print_r(array_replace_keys(['one'=>'apple', 'two'=>'orange'], ['one'=>'ett', 'two'=>'tvo']);
// Output
array(
'ett'=>'apple',
'tvo'=>'orange'
)
mail at romansklenar dot cz
пред 16 години
To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:

<?php
...
$count = func_num_args();

for ($i = 1; $i < $count; $i++) {
   ...
}
...
?>

Check on this code:

<?php
$base = array('id' => NULL, 'login' => NULL, 'credit' => NULL);
$arr1 = array('id' => 2, 'login' => NULL, 'credit' => 5);
$arr2 = array('id' => NULL, 'login' => 'john.doe', 'credit' => 100);
$result = array_replace($base, $arr1, $arr2);

/*
correct output:

array(3) {
   "id" => NULL
   "login" => string(8) "john.doe"
   "credit" => int(100)
}

your output:

array(3) {
   "id" => int(2)
   "login" => NULL
   "credit" => int(5)
}
*/
?>

Function array_replace "replaces elements from passed arrays into the first array" -- this means replace from top-right to first, then from top-right - 1 to first, etc, etc...
sun на drupal точка org
пред 14 години
Instead of calling this function, it's often faster and simpler to do this instead:

<?php
$array_replaced = $array2 + $array1;
?>

If you need references to stay intact:

<?php
$array2 += $array1;
?>
polecat at p0lecat dot com
пред 15 години
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. :) 

<?php
        // Polecat's Multi-dimensional array_replace function
        // Will take all data in second array and apply to first array leaving any non-corresponding values untouched and intact 
        function polecat_array_replace( array &$array1, array &$array2 ) {
            // This sub function is the iterator that will loop back on itself ad infinitum till it runs out of array dimensions
            if(!function_exists('tier_parse')){
                function tier_parse(array &$t_array1, array&$t_array2) {
                    foreach ($t_array2 as $k2 => $v2) {
                        if (is_array($t_array2[$k2])) {
                            tier_parse($t_array1[$k2], $t_array2[$k2]);
                        } else {
                            $t_array1[$k2] = $t_array2[$k2];
                        }
                    }
                    return $t_array1;
                }
            }
            
            foreach ($array2 as $key => $val) {
                if (is_array($array2[$key])) {
                    tier_parse($array1[$key], $array2[$key]);
                } else {
                    $array1[$key] = $array2[$key];
                }
            }
            return $array1;
        }
?>

[I would also like to note] 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:

<?php
$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );

$array2 = array( "food" => "wine");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);
?>

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.
gmastro77 at gmail dot com
12 години пред
In some cases you might have a structured array from the database and one
of its nodes goes like this;

<?php
# a random node structure
$arr    = array( 
    'name'  => 'some name', 
    'key2'  => 'value2', 
    'title' => 'some title', 
    'key4'  => 4, 
    'json'  => '[1,0,1,1,0]'
);

# capture these keys values into given order
$keys   = array( 'name', 'json', 'title' );
?>

Now consider that you want to capture $arr values from $keys.
Assuming that you have a limitation to display the content into given keys
order, i.e. use it with a vsprintf, you could use the following

<?php
# string to transform
$string = "<p>name: %s, json: %s, title: %s</p>";

# flip keys once, we will use this twice
$keys   = array_flip( $keys );

# get values from $arr
$test   = array_intersect_key( $arr, $keys );

# still not good enough
echo vsprintf( $string, $test );
// output --> name: some name, json: some title, title: [1,0,1,1,0]

# usage of array_replace to get exact order and save the day
$test   = array_replace( $keys, $test );

# exact output
echo vsprintf( $string, $test );
// output --> name: some name, json: [1,0,1,1,0], title: some title

?>

I hope that this will save someone's time.
kyberprizrak
пред 11 години
if(!function_exists('array_replace'))
{
  function array_replace()
  {
    $args = func_get_args();
    $num_args = func_num_args();
    $res = array();
    for($i=0; $i<$num_args; $i++)
    {
      if(is_array($args[$i]))
      {
        foreach($args[$i] as $key => $val)
        {
          $res[$key] = $val;
        }
      }
      else
      {
        trigger_error(__FUNCTION__ .'(): Argument #'.($i+1).' is not an array', E_USER_WARNING);
        return NULL;
      }
    }
    return $res;
  }
}
harl на gmail точка ком
пред 1 година
This function *adds* keys from replacement arrays to the new array as well as replacing the values of existing ones, which may not be what you want (or expect).
If you only want actual *replacements* of existing values, when the replacement arrays might have additional keys not in the original, then a quick bit of sanitation is called for:
<?php
$with_replacements = array_replace($original, ...$replacement_arrays);
$with_replacements = array_intersect_key($with_replacements, $original);
?>
vlk dot charles at gmail dot com
пред 1 година
I think it is worth mentioning that the array passed as the first argument is not modified and is left intact. A new array is returned. I think the wording of this documentation could be improved because it suggests that the passed array *is* modified.

If you want to modify your existing array, it is not enough to do:

array_replace($arrayToModify, $arrayWithModifications);

You have to assign the returned value back to it like so:

$arrayToModify = array_replace($arrayToModify, $arrayWithModifications);
lm713
пред 11 години
If the arrays are associative (that is, their keys are strings), then I believe this function is identical to (the older) array_merge.
ricardophp yahoocombr
3 години пред
Concerning the affirmation:
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator

Clearing the fact (it means ...):
If the first array have a key and a value it will not be overlap by the new array. therefore if you have an array like [1=>"alpha", 2=>"beta"] and you got a new array telling [1=>"Alpha", 3=>"Gamma"] the final array will be [1=>"alpha", 2=>"beta", 3=>"Gamma"]. The values of first array will not be modified in the result array.

So, if you are building a concatenation array where the values sometimes overlaps each other keys and you must preserve values you better use array_merge instead "plus" sign
projacore at gmail dot com
пред 10 години
You can also use:

<?php 
$myarray = [
"Orange",
"572" => "Banana",
"omg" => "Chili",
"nevermind" => "mango"
];

$myarray[0] = "NO-Orange"; 
$myarray["572"] = "BANANAPHONE!!!";
$myarray["omg"] = "NO-Chili";

print_r($myarray);

?>

RESULT:
Array
(
    [0] => NO-Orange
    [572] => BANANAPHONE!!!
    [omg] => NO-Chili
    [nevermind] => mango
)

with regards
polecat at p0lecat dot com
пред 15 години
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");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);
 
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.
Анонимен
пред 10 години
The documentation is wrongly phrased: "array_replace() replaces the values of array1"  No replacing is done. A new array is created which looks like the one that would have resulted from the described replacement. 

If you want to augment the set of indices in an array, use 
       array_to_be_modified += array_with_indices_to_add;
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.