How to store a multidimentional array to simple array - php

I have an Array as seen below.
Array
(
[0] =>
[key-1] => Array
(
[key-1-1] => 33
[key-1-2] => 22
)
[key-2] => -1
[key-3] => Array
(
[data] => Array
(
[other_data] => Array
(
[0] => data1
[1] => data2
)
)
)
[key-4] => data3
[key-5] => data4
)
I need to convert these in simpler form of end values as given below and save to an external php file using file_put_contents . I am trying for hours and I tried var_export, multiple foreach and got some degree of success, but not exactly what I want.
$value['key-1-1'] = '33';
$value['key-1-2'] = '22';
$value['other_data'] = array('data1', 'data2');
$value['key-4'] = 'data3';
$value['key-5'] = 'data4';
Can someone help with achieving it ?

You can get somewhat near to your desired output with array_walk_recursive. The troublesome keys are the numeric ones.
If you only have one other_data sub arrays, you could slightly adjust the output below. You'll get overwritten values for like numeric keys. So this method really depends on your data.
<?php
$data =
array
(
'0' =>'',
'key-1' => array
(
'key-1-1' => 33,
'key-1-2' => 22
),
'key-2' => -1,
'key-3' => array
(
'data' => array
(
'other_data' => array
(
'0' => 'data1',
'1' => 'data2'
)
)
),
'key-4' => 'data3',
'key-5' => 'data4'
);
array_walk_recursive($data, function($v, $k) use (&$result) {
$result[$k] = $v;
});
var_export($result);
Output:
array (
0 => 'data1',
'key-1-1' => 33,
'key-1-2' => 22,
'key-2' => -1,
1 => 'data2',
'key-4' => 'data3',
'key-5' => 'data4',
)

Related

Summation of array elements by the indexer [duplicate]

I have an array of subarrays in the following format:
[
'a' => ['id' => 20, 'name' => 'chimpanzee'],
'b' => ['id' => 40, 'name' => 'meeting'],
'c' => ['id' => 20, 'name' => 'dynasty'],
'd' => ['id' => 50, 'name' => 'chocolate'],
'e' => ['id' => 10, 'name' => 'bananas'],
'f' => ['id' => 50, 'name' => 'fantasy'],
'g' => ['id' => 50, 'name' => 'football']
]
And I would like to group it into a new array based on the id field in each subarray.
array
(
10 => array
(
e => array ( id = 10, name = bananas )
)
20 => array
(
a => array ( id = 20, name = chimpanzee )
c => array ( id = 20, name = dynasty )
)
40 => array
(
b => array ( id = 40, name = meeting )
)
50 => array
(
d => array ( id = 50, name = chocolate )
f => array ( id = 50, name = fantasy )
g => array ( id = 50, name = football )
)
)
$arr = array();
foreach ($old_arr as $key => $item) {
$arr[$item['id']][$key] = $item;
}
ksort($arr, SORT_NUMERIC);
foreach($array as $key => $value){
$newarray[$value['id']][$key] = $value;
}
var_dump($newarray);
piece of cake ;)
The following code adapts #Tim Cooper’s code to mitigate Undefined index: id errors in the event that one of the inner arrays doesn’t contain an id:
$arr = array();
foreach($old_arr as $key => $item)
{
if(array_key_exists('id', $item))
$arr[$item['id']][$key] = $item;
}
ksort($arr, SORT_NUMERIC);
However, it will drop inner arrays without an id.
E.g.
$old_arr = array(
'a' => array ( 'id' => 20, 'name' => 'chimpanzee' ),
'b' => array ( 'id' => 40, 'name' => 'meeting' ),
'c' => array ( 'id' => 20, 'name' => 'dynasty' ),
'd' => array ( 'id' => 50, 'name' => 'chocolate' ),
'e' => array ( 'id' => 10, 'name' => 'bananas' ),
'f' => array ( 'id' => 50, 'name' => 'fantasy' ),
'g' => array ( 'id' => 50, 'name' => 'football' ),
'h' => array ( 'name' => 'bob' )
);
will drop the 'h' array completely.
You can also use Arrays::groupBy() from ouzo-goodies:
$groupBy = Arrays::groupBy($array, Functions::extract()->id);
print_r($groupBy);
And result:
Array
(
[20] => Array
(
[0] => Array
(
[id] => 20
[name] => chimpanzee
)
[1] => Array
(
[id] => 20
[name] => dynasty
)
)
[40] => Array
(
[0] => Array
(
[id] => 40
[name] => meeting
)
)
[50] => Array
(
[0] => Array
(
[id] => 50
[name] => chocolate
)
[1] => Array
(
[id] => 50
[name] => fantasy
)
[2] => Array
(
[id] => 50
[name] => football
)
)
[10] => Array
(
[0] => Array
(
[id] => 10
[name] => bananas
)
)
)
And here are the docs for Arrays and Functions.
Here is a function that will take an array as the first argument and a criteria (a string or callback function) as the second argument. The function returns a new array that groups the array as asked for.
/**
* Group items from an array together by some criteria or value.
*
* #param $arr array The array to group items from
* #param $criteria string|callable The key to group by or a function the returns a key to group by.
* #return array
*
*/
function groupBy($arr, $criteria): array
{
return array_reduce($arr, function($accumulator, $item) use ($criteria) {
$key = (is_callable($criteria)) ? $criteria($item) : $item[$criteria];
if (!array_key_exists($key, $accumulator)) {
$accumulator[$key] = [];
}
array_push($accumulator[$key], $item);
return $accumulator;
}, []);
}
Here is the given array:
$arr = array(
'a' => array ( 'id' => 20, 'name' => 'chimpanzee' ),
'b' => array ( 'id' => 40, 'name' => 'meeting' ),
'c' => array ( 'id' => 20, 'name' => 'dynasty' ),
'd' => array ( 'id' => 50, 'name' => 'chocolate' ),
'e' => array ( 'id' => 10, 'name' => 'bananas' ),
'f' => array ( 'id' => 50, 'name' => 'fantasy' ),
'g' => array ( 'id' => 50, 'name' => 'football' )
);
And examples using the function with a string and a callback function:
$q = groupBy($arr, 'id');
print_r($q);
$r = groupBy($arr, function($item) {
return $item['id'];
});
print_r($r);
The results are the same in both examples:
Array
(
[20] => Array
(
[0] => Array
(
[id] => 20
[name] => chimpanzee
)
[1] => Array
(
[id] => 20
[name] => dynasty
)
)
[40] => Array
(
[0] => Array
(
[id] => 40
[name] => meeting
)
)
[50] => Array
(
[0] => Array
(
[id] => 50
[name] => chocolate
)
[1] => Array
(
[id] => 50
[name] => fantasy
)
[2] => Array
(
[id] => 50
[name] => football
)
)
[10] => Array
(
[0] => Array
(
[id] => 10
[name] => bananas
)
)
)
Passing the callback is overkill in the example above, but using the callback finds its use when you pass in an array of objects, a multidimensional array, or have some arbitrary thing you want to group by.
Maybe it's worth to mention that you can also use php array_reduce function
$items = [
['id' => 20, 'name' => 'chimpanzee'],
['id' => 40, 'name' => 'meeting'],
['id' => 20, 'name' => 'dynasty'],
['id' => 50, 'name' => 'chocolate'],
['id' => 10, 'name' => 'bananas'],
['id' => 50, 'name' => 'fantasy'],
['id' => 50, 'name' => 'football'],
];
// Grouping
$groupedItems = array_reduce($items, function ($carry, $item) {
$carry[$item['id']][] = $item;
return $carry;
}, []);
// Sorting
ksort($groupedItems, SORT_NUMERIC);
print_r($groupedItems);
https://www.php.net/manual/en/function.array-reduce.php
Because of how PHP's sorting algorithm treats multidimensional arrays -- it sorts by size, then compares elements one at a time, you can actually use a key-preserving sort on the input BEFORE restructuring. In functional style programming, this means that you don't need to declare the result array as a variable.
Code: (Demo)
asort($array);
var_export(
array_reduce(
array_keys($array),
function($result, $k) use ($array) {
$result[$array[$k]['id']][$k] = $array[$k];
return $result;
}
)
);
I must say that functional programming is not very attractive for this task because the first level keys must be preserved.
Although array_walk() is more succinct, it still requires the result array to be passed into the closure as a reference variable. (Demo)
asort($array);
$result = [];
array_walk(
$array,
function($row, $k) use (&$result) {
$result[$row['id']][$k] = $row;
}
);
var_export($result);
I'd probably recommend a classic loop for this task. The only thing the loop needs to do is rearrange the first and second level keys. (Demo)
asort($array);
$result = [];
foreach ($array as $k => $row) {
$result[$row['id']][$k] = $row;
}
var_export($result);
To be completely honest, I expect that ksort() will be more efficient than pre-loop sorting, but I wanted to a viable alternative.

PHP Match by common key of two multidimentional array and merge the two array with both array key [duplicate]

This question already has answers here:
PHP merge two arrays on the same key AND value
(5 answers)
Closed 4 years ago.
Good evening, I have a little bit problem. I have two array. like
$firstArr = Array(
[0] => Array(
[customer_id] => 11,
[home_delivery] => no,
),
[1] => Array(
[customer_id] => 12,
[home_delivery] => no,
),
[2] => Array(
[customer_id] => 13,
[home_delivery] => no,
),
);
$secondArr = Array(
[0] => Array(
[customer_id] => 11,
[test] => no,
[is_active] => yes,
),
[1] => Array(
[customer_id] => 22,
[test] => no,
[is_active] => yes,
),
);
Now i want to get the result like first array's customer_id match with the second array customer_id. Id two array's customer id is same the the value of second array add with first array otherwise the value will be null. Hope guys you got my point what i want. The output which i want is like the below.
$getResult = Array(
[0] => Array(
[customer_id] => 11,
[home_delivery] => no,
[test] => no,
[is_active] => yes,
),
[1] => Array(
[customer_id] => 12,
[home_delivery] => no,
[test] => '',
[is_active] => '',
),
[2] => Array(
[customer_id] => 13,
[home_delivery] => no,
[test] => '',
[is_active] => '',
),
);
I have tried by this code, but it doesnt work. Please help me.
$mergedArray = array();
foreach ($firstArr as $index1 => $value1) {
foreach ($secondArr as $index2 => $value2) {
if ($array1[$index1]['customer_id'] == $array2[$index2]['customer_id']) {
$mergedArray[] = array_merge($firstArr[$index1], $secondArr[$index2]);
}
}
}
echo "<pre>"; print_r($mergedArray); echo "</pre>";
You can do this :
<?php
$results = [];
// Get all unique keys from both arrays
$keys = array_unique(array_merge(array_keys($firstArr[0]), array_keys($secondArr[0])));
// Make array of common customer_ids
foreach (array_merge($firstArr, $secondArr) as $record) {
$results[$record['customer_id']] = isset($results[$record['customer_id']]) ? array_merge($results[$record['customer_id']], $record) : $record;
}
// Fill keys which are not present with blank strings
foreach ($keys as $key) {
foreach ($results as $index => $result) {
if(!array_key_exists($key, $result)){
$results[$index][$key] = '';
}
}
}
print_r($results);
This is how I would do it:
$firstArr = array (
0 =>
array (
'customer_id' => 11,
'home_delivery' => 'no'
),
1 =>
array (
'customer_id' => 12,
'home_delivery' => 'no'
),
2 =>
array (
'customer_id' => 13,
'home_delivery' => 'no'
)
);
$secondArr = array (
0 =>
array (
'customer_id' => 11,
'test' => 'no',
'is_active' => 'yes'
),
1 =>
array (
'customer_id' => 22,
'test' => 'no',
'is_active' => 'yes'
)
);
$secondKey = array_column($secondArr,'customer_id');
foreach($firstArr as &$value){
$idx2 = array_search($value['customer_id'], $secondKey);
$value = array_merge($value, [
'test' => false !== $idx2 ? $secondArr[$idx2]['test'] : '',
'is_active' => false !== $idx2 ? $secondArr[$idx2]['is_active'] : '',
]);
}
print_r($firstArr);
Output:
Array
(
[0] => Array
(
[customer_id] => 11
[home_delivery] => no
[test] => no
[is_active] => yes
)
[1] => Array
(
[customer_id] => 12
[home_delivery] => no
[test] =>
[is_active] =>
)
[2] => Array
(
[customer_id] => 13
[home_delivery] => no
[test] =>
[is_active] =>
)
)
Sandbox
There are 2 "tricks" I use here, the first, and more important one, is array_column this picks just one column from an array, but the thing is the keys in the resulting array will match the original array. Which we can take advantage of.
The array we get from array column looks like this:
array (
0 => 11,
1 => 22
);
Because the keys match the original array we can use array_search (with the ID) to look up that key, which we can then use in the original array. This gives us an "easier" way to search the second array by flattening it out.
So for example when we look up $firstArr['customer_id'] = 11 in the above array we get the key 0 (which is not boolean false, see below). Then we can take that index and use it for the original array $secondArr and get the values from the other 2 columns.
-Note- that array search returns boolean false when it cant find the item, because PHP treats 0 and false the same we have to do a strict type check !== instead of just !=. Otherwise PHP will confuse the 0 index with being false, which is not something we want.
The second "trick" is use & in the foreach value, this is by reference which allows us to modify the array used in the loop, directly. This is optional as you could just as easily create a new array instead. But I thought I would show it as an option.

PHP Replace Array Values

I have 2 multidimensional arrays that I am working with:
$arr1 =
Array
([type] => characters
[version] => 5.6.7.8
[data] => Array
([Char1] => Array
([id] => 1
[name] =>Char1
[title] =>Example
[tags] => Array
([0] => DPS
[1] => Support))
[Char2] => Array
([id] => 2
[name] =>Char2
[title] =>Example
[tags] => Array
([0] => Tank
[1] => N/A)
)
)
etc...
$arr2=
Array
([games] => Array
([gameId] => 123
[gameType => Match
[char_id] => 1
[stats] => Array
([damage] => 55555
[kills] => 5)
)
([gameId] => 157
[gameType => Match
[char_id] => 2
[stats] => Array
([damage] => 12642
[kills] => 9)
)
etc...
Basically, I need almost all the data in $arr2... but only the Char name from $arr1. How could I merge or add the $arr1['name'] key=>value into $arr2 where $arr1['id'] is equal to $arr2['char_id'] as the "id" field of each array is the same number.
I've attempted using array_merge and array_replace, but I haven't come up with any working solutions. This is also all data that I am receiving from a 3rd party, so I have no control on initial array setup.
Thanks for any help or suggestions!
Actually, this is quite straighforward. (I don't think there a built-in function that does this.)
Loop $arr2 and under it loop also $arr1. While under loop, just add a condition that if both ID's match, add that particular name to $arr2. (And use some referencing & on $arr2)
Consider this example:
// your data
$arr1 = array(
'type' => 'characters',
'version' => '5.6.7.8',
'data' => array(
'Char1' => array(
'id' => 1,
'name' => 'Char1',
'title' => 'Example',
'tags' => array('DPS', 'Support'),
),
'Char2' => array(
'id' => 2,
'name' => 'Char2',
'title' => 'Example',
'tags' => array('Tank', 'N/A'),
),
),
);
$arr2 = array(
'games' => array(
array(
'gameId' => 123,
'gameType' => 'Match',
'char_id' => 1,
'stats' => array('damage' => 55555, 'kills' => 5),
),
array(
'gameId' => 157,
'gameType' => 'Match',
'char_id' => 2,
'stats' => array('damage' => 12642, 'kills' => 9),
),
),
);
foreach($arr2['games'] as &$value) {
$arr2_char_id = $value['char_id'];
// loop and check against the $arr1
foreach($arr1['data'] as $element) {
if($arr2_char_id == $element['id']) {
$value['name'] = $element['name'];
}
}
}
echo '<pre>';
print_r($arr2);
$arr2 should look now like this:
Array
(
[games] => Array
(
[0] => Array
(
[gameId] => 123
[gameType] => Match
[char_id] => 1
[stats] => Array
(
[damage] => 55555
[kills] => 5
)
[name] => Char1 // <-- name
)
[1] => Array
(
[gameId] => 157
[gameType] => Match
[char_id] => 2
[stats] => Array
(
[damage] => 12642
[kills] => 9
)
[name] => Char2 // <-- name
)
)
)
Iterate over $arr2 and add the data to it from the matching $arr1 array value:
$i = 0;
foreach($arr2['games'] as $arr2Game){
$id = $arr2Game['char_id'];
$arr2['games'][$i]['name'] = $arr1['data'][$id]['name'];
$i++;
}
Have not tested this code.
If I'm understanding you correctly, you want to add a name index to each of the arrays within the $arr2['games'] array.
foreach($arr2['games'] as $key => $innerArray)
{
$arr2['games'][$key]['name'] = $arr1['data']['Char'.$innerArray['char_id']]['name'];
}

filter array after merging keys of one array

I am trying to create filtered array 3 using array 1 and array 2.
ARRAY 1
Array (
[title] => value
[title2] => value2
[title3] => value3
)
ARRAY 2
Array (
[0] => Array ( [id] => 20 [title2] => value2 [otherColumn1] => otherValue1)
[1] => Array ( [id] => 21 [title4] => value4 [otherColumn3] => otherValue3)
)
Desired Result after applying the intersection method:
ARRAY 3
Array ( [title2] => value2 )
So far I am unable to achieve the result because array 1 and 2 have non-matching structures. I have tried different techniques but I am unable compare them due to structure differences.
if (!empty($data1['array2'][0])) {
foreach ($data1['array2'] as $key) {
// $filtered= array_intersect($array1,$key);
// print_r($key);
}
// $filtered= array_intersect($array1,$data1['array2']);// if i use $data1['array2'][0] it filters fine but just one row
// print_r($filtered);
}
Any help would be much appreciated. Thank you.
Given the arrays:
$arr = array('title' => 'value', 'title2' => 'value2', 'title3' => 'value3');
$arr2 = array (
0 => array ( 'id' => '20', 'title2' => 'value2', 'otherColumn1' => 'otherValue1'),
1 => array ( 'id' => '21', 'title4' => 'value4', 'otherColumn3' => 'otherValue3'));
You can get your filtered array with this:
$merged = call_user_func_array('array_merge', $arr2);
$filtered = array_intersect($arr, $merged);
If you want to intersect just according to the keys you can use this instead:
$filtered = array_intersect_key($arr, $merged);
you can remove structural difference in the following way
$arr1 = array (
0 => array('title' => 'value', 'title2' => 'value2', 'title3' => 'value3'));
$arr2 = array (
0 => array ( 'id' => '20', 'title2' => 'value2', 'otherColumn1' => 'otherValue1'),
1 => array ( 'id' => '21', 'title4' => 'value4', 'otherColumn3' => 'otherValue3'));

Group rows in an associative array of associative arrays by column value and preserve the original first level keys

I have an array of subarrays in the following format:
[
'a' => ['id' => 20, 'name' => 'chimpanzee'],
'b' => ['id' => 40, 'name' => 'meeting'],
'c' => ['id' => 20, 'name' => 'dynasty'],
'd' => ['id' => 50, 'name' => 'chocolate'],
'e' => ['id' => 10, 'name' => 'bananas'],
'f' => ['id' => 50, 'name' => 'fantasy'],
'g' => ['id' => 50, 'name' => 'football']
]
And I would like to group it into a new array based on the id field in each subarray.
array
(
10 => array
(
e => array ( id = 10, name = bananas )
)
20 => array
(
a => array ( id = 20, name = chimpanzee )
c => array ( id = 20, name = dynasty )
)
40 => array
(
b => array ( id = 40, name = meeting )
)
50 => array
(
d => array ( id = 50, name = chocolate )
f => array ( id = 50, name = fantasy )
g => array ( id = 50, name = football )
)
)
$arr = array();
foreach ($old_arr as $key => $item) {
$arr[$item['id']][$key] = $item;
}
ksort($arr, SORT_NUMERIC);
foreach($array as $key => $value){
$newarray[$value['id']][$key] = $value;
}
var_dump($newarray);
piece of cake ;)
The following code adapts #Tim Cooper’s code to mitigate Undefined index: id errors in the event that one of the inner arrays doesn’t contain an id:
$arr = array();
foreach($old_arr as $key => $item)
{
if(array_key_exists('id', $item))
$arr[$item['id']][$key] = $item;
}
ksort($arr, SORT_NUMERIC);
However, it will drop inner arrays without an id.
E.g.
$old_arr = array(
'a' => array ( 'id' => 20, 'name' => 'chimpanzee' ),
'b' => array ( 'id' => 40, 'name' => 'meeting' ),
'c' => array ( 'id' => 20, 'name' => 'dynasty' ),
'd' => array ( 'id' => 50, 'name' => 'chocolate' ),
'e' => array ( 'id' => 10, 'name' => 'bananas' ),
'f' => array ( 'id' => 50, 'name' => 'fantasy' ),
'g' => array ( 'id' => 50, 'name' => 'football' ),
'h' => array ( 'name' => 'bob' )
);
will drop the 'h' array completely.
You can also use Arrays::groupBy() from ouzo-goodies:
$groupBy = Arrays::groupBy($array, Functions::extract()->id);
print_r($groupBy);
And result:
Array
(
[20] => Array
(
[0] => Array
(
[id] => 20
[name] => chimpanzee
)
[1] => Array
(
[id] => 20
[name] => dynasty
)
)
[40] => Array
(
[0] => Array
(
[id] => 40
[name] => meeting
)
)
[50] => Array
(
[0] => Array
(
[id] => 50
[name] => chocolate
)
[1] => Array
(
[id] => 50
[name] => fantasy
)
[2] => Array
(
[id] => 50
[name] => football
)
)
[10] => Array
(
[0] => Array
(
[id] => 10
[name] => bananas
)
)
)
And here are the docs for Arrays and Functions.
Here is a function that will take an array as the first argument and a criteria (a string or callback function) as the second argument. The function returns a new array that groups the array as asked for.
/**
* Group items from an array together by some criteria or value.
*
* #param $arr array The array to group items from
* #param $criteria string|callable The key to group by or a function the returns a key to group by.
* #return array
*
*/
function groupBy($arr, $criteria): array
{
return array_reduce($arr, function($accumulator, $item) use ($criteria) {
$key = (is_callable($criteria)) ? $criteria($item) : $item[$criteria];
if (!array_key_exists($key, $accumulator)) {
$accumulator[$key] = [];
}
array_push($accumulator[$key], $item);
return $accumulator;
}, []);
}
Here is the given array:
$arr = array(
'a' => array ( 'id' => 20, 'name' => 'chimpanzee' ),
'b' => array ( 'id' => 40, 'name' => 'meeting' ),
'c' => array ( 'id' => 20, 'name' => 'dynasty' ),
'd' => array ( 'id' => 50, 'name' => 'chocolate' ),
'e' => array ( 'id' => 10, 'name' => 'bananas' ),
'f' => array ( 'id' => 50, 'name' => 'fantasy' ),
'g' => array ( 'id' => 50, 'name' => 'football' )
);
And examples using the function with a string and a callback function:
$q = groupBy($arr, 'id');
print_r($q);
$r = groupBy($arr, function($item) {
return $item['id'];
});
print_r($r);
The results are the same in both examples:
Array
(
[20] => Array
(
[0] => Array
(
[id] => 20
[name] => chimpanzee
)
[1] => Array
(
[id] => 20
[name] => dynasty
)
)
[40] => Array
(
[0] => Array
(
[id] => 40
[name] => meeting
)
)
[50] => Array
(
[0] => Array
(
[id] => 50
[name] => chocolate
)
[1] => Array
(
[id] => 50
[name] => fantasy
)
[2] => Array
(
[id] => 50
[name] => football
)
)
[10] => Array
(
[0] => Array
(
[id] => 10
[name] => bananas
)
)
)
Passing the callback is overkill in the example above, but using the callback finds its use when you pass in an array of objects, a multidimensional array, or have some arbitrary thing you want to group by.
Maybe it's worth to mention that you can also use php array_reduce function
$items = [
['id' => 20, 'name' => 'chimpanzee'],
['id' => 40, 'name' => 'meeting'],
['id' => 20, 'name' => 'dynasty'],
['id' => 50, 'name' => 'chocolate'],
['id' => 10, 'name' => 'bananas'],
['id' => 50, 'name' => 'fantasy'],
['id' => 50, 'name' => 'football'],
];
// Grouping
$groupedItems = array_reduce($items, function ($carry, $item) {
$carry[$item['id']][] = $item;
return $carry;
}, []);
// Sorting
ksort($groupedItems, SORT_NUMERIC);
print_r($groupedItems);
https://www.php.net/manual/en/function.array-reduce.php
Because of how PHP's sorting algorithm treats multidimensional arrays -- it sorts by size, then compares elements one at a time, you can actually use a key-preserving sort on the input BEFORE restructuring. In functional style programming, this means that you don't need to declare the result array as a variable.
Code: (Demo)
asort($array);
var_export(
array_reduce(
array_keys($array),
function($result, $k) use ($array) {
$result[$array[$k]['id']][$k] = $array[$k];
return $result;
}
)
);
I must say that functional programming is not very attractive for this task because the first level keys must be preserved.
Although array_walk() is more succinct, it still requires the result array to be passed into the closure as a reference variable. (Demo)
asort($array);
$result = [];
array_walk(
$array,
function($row, $k) use (&$result) {
$result[$row['id']][$k] = $row;
}
);
var_export($result);
I'd probably recommend a classic loop for this task. The only thing the loop needs to do is rearrange the first and second level keys. (Demo)
asort($array);
$result = [];
foreach ($array as $k => $row) {
$result[$row['id']][$k] = $row;
}
var_export($result);
To be completely honest, I expect that ksort() will be more efficient than pre-loop sorting, but I wanted to a viable alternative.

Categories