Replace the element in place with two others in the PHP array

Summary: for array

{a, b, ..., w, x, ..., z} 

insert several elements {m, n, ..., r} at position x , also removing x . Final array:

 {a, b, ..., w, m, n, ..., r, ..., z} 

Have a return array

 $return_arr = array( 'saa'=>'A2223', 'asab'=>'asB', 'wqed'=>'D234', 'wqasee'=>'Esd', 'wqewf'=>'Ffds', 'monwa'=>'monwaaas'//* ); 

it will return a new array if this element exists in this array 'monwa' => 'monwaaas'.And the new array will be the next order of the element we found for example
if we have $ return_arr => then new_array should be

 (add two more element ('hi'=>'HI','hello'=>'HELLO') $new_array = array( 'saa'=>'A2223', 'asab'=>'asB', 'wqed'=>'D234', 'wqasee'=>'Esd', 'wqewf'=>'Ffds', 'hi'=>'HI', 'hello'=>'HELLO' ); 

And if

 $return_arr = array( 'saa'=>'A2223', 'asab'=>'asB', 'monwa'=>'monwaaas',//* 'wqed'=>'D234', 'wqasee'=>'Esd', 'wqewf'=>'Ffds' ); 

new_array should be:

 $new_array = array( 'saa'=>'A2223', 'asab'=>'asB', 'hi'=>'HI', 'hello'=>'HELLO', 'wqed'=>'D234', 'wqasee'=>'Esd', 'wqewf'=>'Ffds' ); 

And so on ...

Does anyone know how to do this?

thanks

+4
source share
3 answers

An example of an online translator .

1) Find the position of this element, 2) delete the element and 3), then insert it into the previous position.

 $pos = array_search_pos($arr, 'monwa'); unset($arr['monwa']); $result = array_insert_at($arr, $pos, array("key1"=>"value1", "key2"=>"value2")); 

Using these functions:

 function array_search_pos($arr, $key) { $i = 0; foreach ($arr as $k => $v) { if ("$k" == "$key") return $i; $i++; } return false; } function array_insert_at($array, $pos, $values) { return array_slice($array, 0, $pos, true) + $values + array_slice($array, $pos, count($array)-$pos, true); } 
+1
source

@Artefacto

I am sure that this will retain the same position.

$ return_array will be placed as a position in $ new_array.

 $new_array = array( 'saa'=>'A2223', 'asab'=>'asB', 'monwa'=>'monwaaas',//* 'wqed'=>'D234', 'wqasee'=>'Esd', 'wqewf'=>'Ffds' ); $element_array = array('hi'=>'HI','hello'=>'HELLO'); foreach($new_array as $key=>$value) { if($key == 'monwa' && $value =='monwaaas') { foreach($element_array as $key1=>$value1) { $return_array[$key1] = $value1; } } else { $return_array[$key] = $value; } } echo "<pre>"; print_r($return_array); echo "<pre>"; 

Try once

0
source

You can do it.

 foreach($new_array as $key=>$value) { if($key == 'monwa' && $value =='monwaaas') { foreach($element_array as $key1=>$value1) { $return_arrat[$key1] = $value1; } } else { $return_array[$key] = $value } } 
-1
source

All Articles