G
G
Gordnev2020-02-04 14:36:07
PHP
Gordnev, 2020-02-04 14:36:07

How to change the values ​​of an array based on the values ​​of another array?

Hello, tell me please, there are two arrays:

First:

Array
(
    [0] => Array
        (
            [name] =>    Смартфон realme XT 8/128GB, синий    
            [price] => null
        )

    [1] => Array
        (
            [name] =>    Смартфон Samsung Galaxy A30 3/32GB, черный    
            [price] => null
        )

    [2] => Array
        (
            [name] =>    Смартфон Tecno Camon 12 Air 3/32GB, синий    
            [price] => null
        )

    [3] => Array
        (
            [name] =>    Смартфон Smartisan U3 Special Edition 4/64GB, черный    
            [price] => null
        )
)


Second:

Array
(
    [0] => Array
        (
            [price] =>      20 990 ₽   
        )

    [1] => Array
        (
            [price] =>      14 390 ₽   
        )

    [2] => Array
        (
            [price] =>      8 990 ₽   
        )

    [3] => Array
        (
            [price] =>      10 995 ₽   
        )
)


How would I combine these two arrays into one so that the price values ​​fall into the first array, in order?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Shamanov, 2020-02-04
@Gordnev

array_merge_recursive/array_replace_recursive ?

O
Oleg Prilepa, 2020-02-04
@OAPrilepa

foreach($array1 as $key => &$value) {
    $value['price'] = $array2[$key]['price'];
}
unset($value);

T
Tigran196296, 2020-02-04
@Tigran196296

function test($array1, $array2)
{
    foreach ($array2 as $key => $price) {
        if (array_key_exists($key, $array1)) {
            $array1[$key]['price'] = $price['price'];
        }
    }
    return $array1;
}
echo '<pre>';
var_dump(test($array1, $array2));
echo '</pre>';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question