2

I got an array of objects from Laravel query builder:

[
 {
   "name": "John",
   "code": "006"
 },
 {
   "name": "James"
   "code": "007"
 },
 {
   "name": "Jone"
   "code": "008"
 }
]

I wanna turn it into this:

[
  "John"  => "006",
  "James" => "007",
  "Jone"  => "008"
]
1
  • can you share that laravel code ? Commented Aug 7, 2018 at 4:47

3 Answers 3

3

If you have an array:

\Illuminate\Support\Arr::pluck($array, 'code', 'name');
array_pluck($array, 'code', 'name');

If you have a collection:

$collection->pluck('code', 'name');

You could have also plucked from the query:

$query->pluck('code', 'name'); // instead of the `get` call 

Depending upon Laravel version this method could be lists

Laravel 5.6 Docs - Helpers - array_pluck

Laravel 5.6 Docs - Collections - Method pluck

Laravel 5.6 Docs - Query Builder - Retrieving Results

Sign up to request clarification or add additional context in comments.

1 Comment

pluck will work too. Just need to comver the json string first.
2

You can try this -

// decode the json
$data = json_decode($array, true);
$final = array_column($data, "code", "name");

json_decode will decode the JSON string and return array.

array_column will return the values for provided keys.

3 Comments

For that case it will never work. Then may be an sub array.
You don't need to use array_column twice or array_combine. $final = array_column($data, "code", "name"); is the same as your code.
Totally forgot the third parameter. Thanks.
1

If there is multiple persons with the same name you can't use array_combine.

This method uses array_intersect to find the codes that match the name and create a subarray on each name whith all the codes.

$arr = json_decode($str, true);
$names = array_column($arr, "name");
$codes = array_column($arr, "code");

foreach(array_unique($names) as $name){
    $new[$name] = array_intersect_key($codes, array_intersect($names, [$name]));
}
var_dump($new);

output:

array(3) {
  ["John"]=>
  array(2) {
    [0]=>
    string(3) "006"
    [3]=>
    string(3) "010"
  }
  ["James"]=>
  array(1) {
    [1]=>
    string(3) "007"
  }
  ["Jone"]=>
  array(1) {
    [2]=>
    string(3) "008"
  }
}

https://3v4l.org/Tj4Dd

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.