简体   繁体   中英

PHP array adding new data in specific place

I have a php array called $data with keys as numeric values, as below:

$data['5']="Data 5";
$data['6']="Data 6";
$data['9']="Data 9";

I then have an addition to this variable as follows:

$data['new']="New Data";

But i need to place this new data into the $data array before a specific key that is returned by $key variable.

So for example if $key=6 then the new data addition needs to be added just before the 6 in the $data array.

Any ideas how I can achieve this?

Thanks

John, if you want to add it on particular position than you can try code like this.

$data['5']="Data 5";
$data['6']="Data 6";
$data['9']="Data 9";

$additionData['new']="New Data";
function array_insert($arr, $insert, $position) {
    $i =0;
    foreach ($arr as $key => $value) {
            if ($i == $position) {
                    foreach ($insert as $ikey => $ivalue) {
                            $ret[$ikey] = $ivalue;
                    }
            }
            $ret[$key] = $value;
            $i++;
    }
    return $ret;
}

  $data = array_insert($data,$additionData,2);
  echo "<pre>";
  print_r($data);

and call this function like array_insert($data,$additionData,2);

2 is the position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM