Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 942
Alexandre Thebaldi Avatar asked Nov 17 '25 04:11

Alexandre Thebaldi


1 Answers

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
    )
like image 56
Always Sunny Avatar answered Nov 18 '25 18:11

Always Sunny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!