Jump to content

Recommended Posts

Hey guys,

 

Looking for a push in the right direction here. If i have an array like such:

 

$array[0] = olddata
$array[1] = olddata
$array[2] = olddata
$array[3] = olddata
$array[4] = olddata
$array[5] = olddata
$array[6] = olddata

 

and want to insert data in between on lines 1,2,3,4,5 <b>without</b> overwriting the data so my array looks like such:

 

$array[0] = olddata
$array[1] = newdata
$array[2] = newdata
$array[3] = newdata
$array[4] = newdata
$array[5] = newdata
$array[6] = olddata(used to be $array[1])
$array[6] = olddata(used to be $array[2])
$array[6] = olddata(used to be $array[3])
$array[6] = olddata(used to be $array[4])
$array[6] = olddata(used to be $array[5])

 

How would i go about it..? I'm basically pushing the other data down. The amount i will want to insert will be different every time and the lines i will want to insert the data into will be different every time. However on the upside the new data will always be straight after each other (ie insert new data on lines 2,3,4,5 and push old data down to 6,7,8,9 <b>not</b> insert on lines 2,4,9,6 ect..) So obviously i need some loopishly.. but just not sure where to start.. any suggestions..?

 

Thanks lads. You guys are saviors.

Link to comment
https://forums.phpfreaks.com/topic/53598-array-inserting/
Share on other sites

<?php
function insertArray($array, $addDataArr, $pos) {
    $newKey = -1;
    foreach ($array as $key => $val) {
          if ($key == $pos) { 
                foreach ($addDataArr as $val) {
                      $newArray[$key++] = $val;
                }
                $newKey = $key;     
          }else {
              if (isset($newKey) && $newKey != -1) {
                    $newArray[$newKey++] = $val;
              }else {
                    $newArray[$key] = $val;
              }
          }
    }
}
?>

 

Probably not the best way but I think it works, I also think there is something like www.php.net/array_merge

 

But yea, I think the above will work, untested.

Link to comment
https://forums.phpfreaks.com/topic/53598-array-inserting/#findComment-264952
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.