简体   繁体   中英

How to specify array keys from a map

I need to construct an array that have custom keys based on another array.

Algorithm idea:

  $list = [10, 20, 30];

  $map = array_map(function ($item) {
    return [
      $item => 'banana' . time(),
    ];
  }, $list);

What I would expected $map to be:

  [
    10 => 'banana 12345',
    20 => 'banana 12346',
    30 => 'banana 12347',
  ]

What (obviously) $map is:

  [
    0 => [
      10 => 'banana 12345',
    ],
    1 => [
      20 => 'banana 12346',
    ],
    2 => [
      30 => 'banana 12347',
    ],        
  ]

How to specify the array keys for this situation?

Use array_fill_keys function

$list = [10, 20, 30];
$arr = array_fill_keys($list, 'banana');

Update

$list = [10, 20, 30];

$map = array_map(function ($item) {
            return 'banana' . time();}, 
         array_fill_keys($list));

If I don't misunderstood your requirement. I've couple of approach.Here both should work for you.

1st Approach (Mine)

$keys = [10, 20, 30];
$initials = 'banana'
$time = time();
$array = array_fill_keys($keys, $initials." " .$time);
print '<pre>';
print_r($array);
print '</pre>';

Output:

Array
(
    [10] => banana 1514305494
    [20] => banana 1514305494
    [30] => banana 1514305494
)

2nd Approach (Yours)

$list = [10, 20, 30];
$time = time();
$map = array_map(function ($item) use ($time){
    return [$item => 'banana ' . $time];
  }, $list);

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($map)) as $k=>$v){
    $singleDimension[$k]=$v;
}
print '<pre>';
print_r($singleDimension);
print '</pre>';

Output:

Array
    (
        [10] => banana 1514305494
        [20] => banana 1514305494
        [30] => banana 1514305494
    )

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