How to return array with custom key mapWithKeys?
Asked Answered
T

1

12

This is code that iterate collection in Laravel:

$usersData = $users->mapWithKeys(function ($item) {
    return [$item->id => array("name" => $item->name, "email" => $item->email, "id" => $item->id)];
 });

I tried to get array $usersData with custom key and value as array.

But in result I get this:

array:1 [  0 => array:3 [    "name" => "Doctor"    "email" => "[email protected]"    "id" => 2  ]]

Instead key 2 I have key 0 for element of array.

Topography answered 11/10, 2017 at 21:1 Comment(0)
A
31

I believe you are doing something wrong. Take a look at this:

$users = collect([
    (object)['id' => 5, 'value' => 30, 'something' => 'else'],
    (object)['id' => 6, 'value' => 40, 'something' => 'else2'],
    (object)['id' => 7, 'value' => 50, 'something' => 'else3'],
    (object)['id' => 8, 'value' => 60, 'something' => 'else4'],
    (object)['id' => 9, 'value' => 70, 'something' => 'else5'],
    (object)['id' => 30, 'value' => 90, 'something' => 'else6'],
]);

$users = $users->mapWithKeys(function($user, $key) {
    return [$user->id => $user];
});

dd($users);

The result here is:

Collection {#374
  #items: array:6 [
    5 => {#364
      +"id": 5
      +"value": 30
      +"something": "else"
    }
    6 => {#363
      +"id": 6
      +"value": 40
      +"something": "else2"
    }
    7 => {#362
      +"id": 7
      +"value": 50
      +"something": "else3"
    }
    8 => {#361
      +"id": 8
      +"value": 60
      +"something": "else4"
    }
    9 => {#356
      +"id": 9
      +"value": 70
      +"something": "else5"
    }
    30 => {#357
      +"id": 30
      +"value": 90
      +"something": "else6"
    }
  ]
}

exactly as expected. Are you sure you don't display result using for example dd($users->values()) ? Because values() will remove those keys and in that case you will get indexes from 0 to 5.

It your case doesn't work, try with this - this should work and should give you idea what you are doing wrong.

Asexual answered 11/10, 2017 at 21:51 Comment(1)
you're a G, an absolute Gangster.Sorn

© 2022 - 2024 — McMap. All rights reserved.