简体   繁体   中英

How to copy array keys to another array, and replace values with empty array?

I have an array, fe:

$arr = array(
    4 => 'some value 1',
    7 => 'some value 2',
    9 => 'some value 3',
    12 => 'some value 4',
    13 => 'some value 5',
    27 => 'some value 6',
    41 => 'some value 7'
)

I need to create another array, where values will be array, but the keys will be the same; like this:

$arr = array(
    4 => array(),
    7 => array(),
    9 => array(),
    12 => array(),
    13 => array(),
    27 => array(),
    41 => array()
)

Is there some build-in function in PHP for do that? array_keys() didn't help me:

var_dump(array_keys($arr));

Returned:

array(7) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
  [5]=>
  int(5)
  [6]=>
  int(6)
}

Try this . You can use array_fill_keys() for more info follow this link

$arr = array(
    4 => 'some value 1',
    7 => 'some value 2',
    9 => 'some value 3',
    12 => 'some value 4',
    13 => 'some value 5',
    27 => 'some value 6',
    41 => 'some value 7'
);
$keys=array_keys($arr);

$filledArray=array_fill_keys($keys,array());
print_r($filledArray);

This should work for you:

Just array_combine() your array_keys() from the old array, with an array_fill() 'ed array full of empty arrays.

<?php

    $newArray = array_combine(array_keys($arr), array_fill(0, count($arr), []));
    print_r($newArray);

?>

output:

Array
(
    [4] => Array ()  
    [7] => Array ()    
    [9] => Array ()    
    [12] => Array ()    
    [13] => Array ()    
    [27] => Array ()
    [41] => Array ()

)

Change values to array saving keys:

$arr2 = array_map(function ($i){
    return array();
}, $arr);

result

Array
(
    [4] => Array ( )  
    [7] => Array ( )    
    [9] => Array ( )    
    [12] => Array ( )    
    [13] => Array ( )    
    [27] => Array ( )
    [41] => Array ( )

)

Try this:

foreach($arr as $key => $value) {
  $array[$key] = array('a','b','c');
}

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