0

I want to insert the values from the first array inside the second array, where the key's name is [cost]:

$newcosts

Array ( 
    [0] => 52.68
    [1] => 7414.68
    [2] => 2471.56
 )

$mainarray

[0] => Array (
    [id] => 2
    [date] => 15.12.2020
    [cost] => 60.00
    )
[1] => Array (
    [id] => 1
    [date] => 22.12.2020
    [cost] => 60.00
    )
[2] => Array (
    [id] => 3
    [date] => 24.12.2020
    [cost] => 22.00
    )

I tried the following:

foreach ($mainarray as $key => $value) {
    $values[] = $value['cost'];
    $new_array[] = str_replace($values, $newcosts, $value);
}

for some reason, this is not showing the right data and sometime they get repeated. this is an example:

[0] => Array (
    [id] => 2
    [date] => 15.12.2020
    [cost] => 52.68
    )
[1] => Array (
    [id] => 1
    [date] => 22.12.2020
    [cost] => 52.68
    )
[2] => Array (
    [id] => 3
    [date] => 24.12.2020
    [cost] => 2471.56
    )

Hope someone could help me on that. Thank you very much!

0

3 Answers 3

3

Just use the mainarray's index to replace the $newcosts into the array.

foreach ($mainarray as $index => $subarray) {
    $mainarray[$index]['cost'] = $newcosts[$index];
}

Because you will have an unused variable $subarray this way, it would be nicer to use a for loop:

for ($i = 0; $i < count($mainarray); $i++) {
   $mainarray[$i]['cost'] = $newcosts[$i];
}
Sign up to request clarification or add additional context in comments.

Comments

3

user foreach to get value of $newcosts and then in loop replace value of price by id in foreach loop you shuld replace value of $mainarray

foreach($newcosts as $itme => $value){
 $mainarray [$itme ]['cost'] = $value;
}

Comments

0

Why are you using str_replace to replace float value ?

You can also index your array like this

for ($idx = 0; $idx <= count($mainarray); $idx++) {
     $mainarray[$idx]['cost'] = $mainarray[$idx];
}

edit : same solution as above

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.