If I have master array like this:
array(5) {
[0]=>
string(4) "1039"
[1]=>
string(1) "1"
[2]=>
string(4) "2015"
[3]=>
string(1) "0"
[4]=>
string(0) ""
}
array(5) {
[0]=>
string(4) "1040"
[1]=>
string(1) "1"
[2]=>
string(4) "2015"
[3]=>
string(1) "0"
[4]=>
string(0) ""
}
array(5) {
[0]=>
string(4) "1041"
[1]=>
string(1) "1"
[2]=>
string(4) "2015"
[3]=>
string(1) "0"
[4]=>
string(0) ""
}
I want to replace every 4th key value with the value from another array.
Second arrays is:
array(156) {
[0]=>
string(12) "Some title 1"
[1]=>
string(12) "Some title 2"
[2]=>
string(12) "Some title 3"
}
So the new array should look like this:
array(5) {
[0]=>
string(4) "1039"
[1]=>
string(1) "1"
[2]=>
string(4) "2015"
[3]=>
string(1) "Some title 1"
[4]=>
string(0) ""
}
array(5) {
[0]=>
string(4) "1040"
[1]=>
string(1) "1"
[2]=>
string(4) "2015"
[3]=>
string(1) "Some title 2"
[4]=>
string(0) ""
}
array(5) {
[0]=>
string(4) "1041"
[1]=>
string(1) "1"
[2]=>
string(4) "2015"
[3]=>
string(1) "Some title 3"
[4]=>
string(0) ""
}
How this can be achieved ? I have tried looping with foreach for the first one and then inside again foreach for the second one, and then string_replace
, array_replace
and stuff like that, but never got it to work. Thanks in advance
if($masterArray) {
foreach($masterArray as $mKey=>$mValue) {
if(isset($secondArray[$mKey]) {
$masterArray[$mKey][3] = $secondArray[$mKey];
}
}
}
Just use the fact that you can index.
for($i = 0; $i < count($second_array); $i++)
{
$array_to_update = $arraylist[$i]; //get one of the arrays that you want to update
$array_to_update[3] = $second_array[$i]; // 0-based index, so [3] is actually your 4th value. Set it to the $i-th value in your second array.
}
Doneski's.
NOTE: I assumed you have the arrays you want to update in some other array called arraylist. If you do not have it in that format either get it to be like that or use a different approach. Also, I assumed that the arraylist and the second_array (which contains the strings you want to add) are of the same length. If this is not the case, make sure you're not going to get index out of bound errors.
In your case you can use this code:
$myArray = array_replace($myArray ,array_fill_keys(array_keys($myArray , $value),$replacement));
if(count($masterArr) > 0) {
foreach($masterArr as $key => $value) {
if( isset($masterArr[$key][3]) && isset($secondArr[$key]) {
$masterArr[$key][3] = $secondArr[$key];
continue; # Will help to neglect unwanted loops
}
}
}