简体   繁体   中英

how to delete a key in array and rebuild the array in php

I got the following array

array(3) {
  [0] =>
  array(1) {
    'Investment' =>
    array(15) {
      'id' =>
     string(36) "53d64bec-031c-4732-b2e0-755799154b1b" ...

I would like to remove the Investment key and do the new array should be

    array(3) {
  [0] =>
  array(15) {
      'id' =>
     string(36) "53d64bec-031c-4732-b2e0-755799154b1b" ...

how do I do it?

I would pass the array to array_map as such:

$array = [
    [ 'Investment' => [ 'id' => '13d64bec-031c-4732-b2e0-755799154b1b' ] ],
    [ 'Investment' => [ 'id' => '23d64bec-031c-4732-b2e0-755799154b1b' ] ],
    [ 'Investment' => [ 'id' => '33d64bec-031c-4732-b2e0-755799154b1b' ] ],
    [ 'Investment' => [ 'id' => '43d64bec-031c-4732-b2e0-755799154b1b' ] ]
];

$mappedArray = array_map(function($val) {
    return $val['Investment'];
}, $array);

store investment array in temp variable and unset as similar as given below

$tempArr = // 0 index of your array
foreach($tempArr as $key=>$val){
     if(!empty($val['Investment'])){
       $temp = $val['Investment'];
    unset($val['Investment']);
    $val[] = $temp;
}

}

You can use array_map() and return the value of the 'Investment' key for each item.

$newArray = array_map(function($item) {
    return $item['Investment'];
}, $oldArray);

If you do not want to copy the array, you can possibly try to use array_walk() .

Edit: solution using array_walk()

array_walk($oldArray, function(&$item) {
    $item = $item['Investment'];
});

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