PHP sorting object array by certain criteria? - php

I have something like this:
$i = 0;
foreach($tracks['results'] as $track){
$trackName[$i] = $track['name'];
$trackPlaycount[$track['name']] = $track['playcount'];
$trackPercent[$track['name']] = $track['percent'];
$i++;
}
$this->trackName = $trackName;
$this->trackPlaycount = $trackPlaycount;
$this->trackPercent = $trackPercent;
how could I sort these objects by playcount? From what I have read so far I understand I should probably create a compare function and then make it work with usort(), right? But I'm not quite sure how to accomplish that...
thank you
edit: ok, so now I've got it like this:
public function firstmethod(){
// there are some more parameters here of course
// but they worked before, not important for the problem
$i = 0;
foreach($tracks['results'] as $track){
$trackName[$i] = $track['name'];
$trackPlaycount[$track['name']] = $track['playcount'];
$trackPercent[$track['name']] = $track['percent'];
// this part is new
$tracksArray[$i] = array(
'name' => $trackName[$i],
'playcount' => $trackPlaycount[$track['name']],
'percentage' => $trackPercent[$track['name']]
);
$i++;
}
usort($tracksArray, array($this, 'sortByCount'));
$i = 0;
// this is to put the new sorted array into the old variables?
foreach($tracksArray as $temp){
$trackName[$i] = $temp['name'];
$trackPlaycount[$trackName[$i]] = $temp['playcount'];
$trackPercent[$trackName[$i]] = $temp['percentage'];
$i++;
}
$this->trackName = $trackName;
$this->trackPlaycount = $trackPlaycount;
$this->trackPercent = $trackPercent;
}
public function sortByCount($a, $b){
if($a["playcount"] == $b["playcount"]) {
return 0;
}
return ($a["playcount"] < $b["playcount"]) ? -1 : 1;
}
this now works...
thank you everyone

usort example:
In the custom function you just access the array key you care about like this:
?php
$people = array(
array('id' => 1, 'name' => 'John', 'age' => 12),
array('id' => 2, 'name' => 'Mary', 'age' => 14),
array('id' => 3, 'name' => 'Aaaaaadam', 'age' => 15)
);
usort($people, "sortByName");
var_dump($people);
usort($people, "sortByAge");
var_dump($people);
function sortByName($a, $b) {
return strcmp($a["name"], $b["name"]);
}
function sortByAge($a, $b) { // or playcount or whatever
if($a["age"] == $b["age"]) {
return 0;
}
return ($a["age"] < $b["age"]) ? -1 : 1;
}
prints the sorted array (only pasted one so it's not getting to long, other output accordingly sorted by age)
array(3) {
[0]=>
array(3) {
["id"]=>
int(3)
["name"]=>
string(9) "Aaaaaadam"
["age"]=>
int(15)
}
[1]=>
array(3) {
["id"]=>
int(1)
["name"]=>
string(4) "John"
["age"]=>
int(12)
}
[2]=>
array(3) {
["id"]=>
int(2)
["name"]=>
string(4) "Mary"
["age"]=>
int(14)
}
}

You could also use an SplMaxHeap for this. Borrowing #edorian's $people array, you can do
class SortByAge extends SplMaxHeap
{
function compare($a, $b)
{
return $a['age'] - $b['age'];
}
}
$sort = new SortByAge;
foreach($people as $person) {
$sort->insert($person);
}
print_r(iterator_to_array($sort));
This should perform somewhat better than usort.

Related

Generating all combinations of an array of search keywords without fixed size in php [duplicate]

Given a PHP array of strings, e.g.:
['peter', 'paul', 'mary']
How to generate all possible permutations of elements of this array? i.e.:
peter-paul-mary
peter-mary-paul
paul-peter-mary
paul-mary-peter
mary-peter-paul
mary-paul-peter
function pc_permute($items, $perms = array()) {
if (empty($items)) {
echo join(' ', $perms) . "<br />";
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
pc_permute($newitems, $newperms);
}
}
}
$arr = array('peter', 'paul', 'mary');
pc_permute($arr);
or
function pc_next_permutation($p, $size) {
// slide down the array looking for where we're smaller than the next guy
for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { }
// if this doesn't occur, we've finished our permutations
// the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1)
if ($i == -1) { return false; }
// slide down the array looking for a bigger number than what we found before
for ($j = $size; $p[$j] <= $p[$i]; --$j) { }
// swap them
$tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;
// now reverse the elements in between by swapping the ends
for (++$i, $j = $size; $i < $j; ++$i, --$j) {
$tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;
}
return $p;
}
$set = split(' ', 'she sells seashells'); // like array('she', 'sells', 'seashells')
$size = count($set) - 1;
$perm = range(0, $size);
$j = 0;
do {
foreach ($perm as $i) { $perms[$j][] = $set[$i]; }
} while ($perm = pc_next_permutation($perm, $size) and ++$j);
foreach ($perms as $p) {
print join(' ', $p) . "\n";
}
http://docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm
This does what you need, in place, i.e. without allocating any additional memory. It stores the resulting permutations the $results array. I am pretty confident that this is the fasted way to solve the task.
<?php
function computePermutations($array) {
$result = [];
$recurse = function($array, $start_i = 0) use (&$result, &$recurse) {
if ($start_i === count($array)-1) {
array_push($result, $array);
}
for ($i = $start_i; $i < count($array); $i++) {
//Swap array value at $i and $start_i
$t = $array[$i]; $array[$i] = $array[$start_i]; $array[$start_i] = $t;
//Recurse
$recurse($array, $start_i + 1);
//Restore old order
$t = $array[$i]; $array[$i] = $array[$start_i]; $array[$start_i] = $t;
}
};
$recurse($array);
return $result;
}
$results = computePermutations(array('foo', 'bar', 'baz'));
print_r($results);
This works in PHP>5.4. I used a anonymous function for recursion to keep the main function's interface clean.
I needed something similar and found this post while looking. Landed up writing the following which does the job.
With 8 items it works fairly quickly (a bit quicker than the examples I found online), but go beyond that and the run time ramps up rapidly. If you only need to output the results it could be made quicker and the memory use reduced massively.
print_r(AllPermutations(array('peter', 'paul', 'mary')));
function AllPermutations($InArray, $InProcessedArray = array())
{
$ReturnArray = array();
foreach($InArray as $Key=>$value)
{
$CopyArray = $InProcessedArray;
$CopyArray[$Key] = $value;
$TempArray = array_diff_key($InArray, $CopyArray);
if (count($TempArray) == 0)
{
$ReturnArray[] = $CopyArray;
}
else
{
$ReturnArray = array_merge($ReturnArray, AllPermutations($TempArray, $CopyArray));
}
}
return $ReturnArray;
}
Note that the number of permutations is the factorial of the number of items in the array. For 3 items there are 6 permutations, for 4 there are 24, for 5 there are 120, for 6 there are 720, etc.
EDIT
Came back to have a look at this and done some revisions.
Below is an improved version of this function, which uses less storage and is quicker (quicker than other solutions I have seen).
It takes the return array as a parameter, passing it through by reference. This reduces the amount of duplication of data as it runs through.
function AllPermutations($InArray, &$ReturnArray = array(), $InProcessedArray = array())
{
if (count($InArray) == 1)
{
$ReturnArray[] = array_merge($InProcessedArray, $InArray);
}
else
{
foreach($InArray as $Key=>$value)
{
$CopyArray = $InArray;
unset($CopyArray[$Key]);
AllPermutations2($CopyArray, $ReturnArray, array_merge($InProcessedArray, array($Key=>$value)));
}
}
}
I expanded a bit on the answer of Jack
function pc_permute($items, $perms = [],&$ret = []) {
if (empty($items)) {
$ret[] = $perms;
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$this->pc_permute($newitems, $newperms,$ret);
}
}
return $ret;
}
This will actually return an array with all possible permutations.
$options = ['startx','starty','startz','endx','endy','endz'];
$x = $this->pc_permute($options);
var_dump($x);
[0]=>
array(6) {
[0]=>
string(6) "startx"
[1]=>
string(6) "starty"
[2]=>
string(6) "startz"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[1]=>
array(6) {
[0]=>
string(6) "starty"
[1]=>
string(6) "startx"
[2]=>
string(6) "startz"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[2]=>
array(6) {
[0]=>
string(6) "startx"
[1]=>
string(6) "startz"
[2]=>
string(6) "starty"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[3]=>
array(6) {
[0]=>
string(6) "startz"
[1]=>
string(6) "startx"
[2]=>
string(6) "starty"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[4]=>
array(6) {
[0]=>
string(6) "starty"
[1]=>
string(6) "startz"
[2]=>
string(6) "startx"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[5]=>
array(6) {
[0]=>
string(6) "startz"
[1]=>
string(6) "starty"
[2]=>
string(6) "startx"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[6]=> ................ a lot more
I found it a bit more usefull to get an array back instead of a string. Then it's up to the using application how to handle the resutls(to join them, or something else)
Simple version with recursion and no artificial extra arguments:
function permuteArray(array $input) {
$input = array_values($input);
// permutation of 1 value is the same value
if (count($input) === 1) {
return array($input);
}
// to permute multiple values, pick a value to put in the front and
// permute the rest; repeat this with all values of the original array
$result = [];
for ($i = 0; $i < count($input); $i++) {
$copy = $input;
$value = array_splice($copy, $i, 1);
foreach (permuteArray($copy) as $permutation) {
array_unshift($permutation, $value[0]);
$result[] = $permutation;
}
}
return $result;
}
This algorithm is nice and instructive how you would do it on paper, but otherwise very inefficient as it calculates same permutations multiple times. Not to say that it is very impractical for calculating permutations of larger arrays as the space and number of calculations grow exponentially.
Recursive function to get all permutations of an array.
Call getPermutations($arr) to get an array of arrays with all the permutations.
function getPermutations ($arr)
{
assert (!empty($arr));
if (count($arr)==1)
{
return [$arr];
}
$first=array_shift($arr);
$permutations=getPermutations($arr);
$result=[];
foreach ($permutations as $permutation)
{
$result=array_merge($result, addElementInAllPositions($permutation, $first));
}
return $result;
}
function addElementInAllPositions ($arr, $element)
{
$i=0;
$result=[];
while ($i<=count($arr))
{
$result[]=array_merge(array_slice($arr,0,$i), [$element], array_slice($arr, $i));
$i++;
}
return $result;
}
Here is another variant based on this article: https://docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm
public static function get_array_orders( $arr ) {
$arr = array_values( $arr ); // Make sure array begins from 0.
$size = count( $arr ) - 1;
$order = range( 0, $size );
$i = 0;
$orders = [];
do {
foreach ( $order as $key ) {
$orders[ $i ][] = $arr[ $key ];
}
$i ++;
} while ( $order = self::get_next_array_order( $order, $size ) );
return $orders;
}
protected static function get_next_array_order( $order, $size ) {
// slide down the array looking for where we're smaller than the next guy
$i = $size - 1;
while ( isset( $order[ $i ] ) && $order[ $i ] >= $order[ $i + 1 ] ) {
$i --;
}
// if this doesn't occur, we've finished our permutations, the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1)
if ( $i == - 1 ) {
return false;
}
// slide down the array looking for a bigger number than what we found before
$j = $size;
while( $order[ $j ] <= $order[ $i ] ){
$j--;
}
// swap them
$tmp = $order[ $i ];
$order[ $i ] = $order[ $j ];
$order[ $j ] = $tmp;
// now reverse the elements in between by swapping the ends
for ( ++ $i, $j = $size; $i < $j; ++ $i, -- $j ) {
$tmp = $order[ $i ];
$order[ $i ] = $order[ $j ];
$order[ $j ] = $tmp;
}
return $order;
}
Example:
$langs = ['en', 'fr', 'ru'];
$orders = self::get_array_orders( $langs );
print_r($orders);
Outputs:
Array (
[0] => Array
(
[0] => en
[1] => fr
[2] => ru
)
[1] => Array
(
[0] => en
[1] => ru
[2] => fr
)
[2] => Array
(
[0] => fr
[1] => en
[2] => ru
)
[3] => Array
(
[0] => fr
[1] => ru
[2] => en
)
[4] => Array
(
[0] => ru
[1] => en
[2] => fr
)
[5] => Array
(
[0] => ru
[1] => fr
[2] => en
)
)

Get lowest key - array value in multidimensional array PHP

So, I got array that looks something like this:
[65]=>
array(2) {
[0]=>
array(2) {
["p"]=>
float(234)
["sp"]=>
float(234)
}
[1]=>
array(2) {
["p"]=>
float(53)
["sp"]=>
float(5)
}
[2]...
[3]...
}
The idea is to go through each of 0 - N values of key 65 array, and only keep one with smallest "p", others should be removed / filtered out.
This should be done in PHP.
Anyone has any idea?
I tried something like this:
$array = array_filter($array, function ($value, $key) use ($a) {
return $a['p'] <= $value['p'];
}, ARRAY_FILTER_USE_BOTH);
where $value is 1 of elements inside 65 keyed-array and $a is current pair that is being added dynamically. So when ever its added, I go through existing elements and if its lowest, it should stay, and others get instant filtered out, but if its higher, it should automatically be filtered out.
Thank you!
You can use array_reduce() to get the lowest "p"-value:
$arr = [
65 => [
["p" => 234, "sp" => 234],
["p" => 53, "sp" => 5],
["p" => 530, "sp" => 5],
]
];
function getLowestKey($carry, $item) {
if ($item['p'] < $carry || !$carry) {
$carry = $item['p'];
}
return $carry;
}
$lowestKey = array_reduce($arr[65], 'getLowestKey');
var_dump($lowestKey); // int(53)
Edit:
I just noticed there is a second part to your question, sorry about that. Once you found out the "lowest p" you can then just filter the array with that knowledge:
$lowestPs = array_filter($arr[65], function($item) use ($lowestKey) {
return $item['p'] == $lowestKey;
});
var_dump($lowestPs);
/*
array(2) {
[1]=>
array(2) {
["p"]=>
int(53)
["sp"]=>
int(5)
}
[2]=>
array(2) {
["p"]=>
int(53)
["sp"]=>
int(5)
}
}
*/
This solution works even if multiple entries have the same lowest "p" value (like 53 in the above example), all of those will stay.
Use array_column() to do an array_multisort() on the 'p' value for the records inside key 65.
<?php
$col = 'p'; // set the column you want to order on
$column = array_column($arr[65], $col);
array_multisort($column, SORT_ASC, $arr[65]);
$arr[65] = $arr[65][0]; // only keep the record with lowest 'p' value
demo
If have more than 1 nested levels, you might also use a recursive approach checking the value of p, keeping the array with the lowest value.
$arrays = [
65 => [
["p" => 234, "sp" => 234],
[
["p" => 53,"sp" => 5],
[
["p" => 54,"sp" => 1],
["p" => 53,"sp" => 7],
]
], [
"p" => 255,
"sp" => 235
],
]
];
function loop($array, &$coll = [], &$min = null)
{
foreach ($array as $key => $value) {
if (is_array($value)) {
loop($value, $coll, $min);
} elseif ($key === "p") {
if ($min === null) $min = $value;
if ($min > $value) {
$coll = [$array];
$min = $value;
continue;
}
if($value === $min) $coll[] = $array;
}
}
return $coll;
}
$arrays[65] = loop($arrays[65]);
var_dump($arrays);
Output
array(1) {
[65]=>
array(2) {
[0]=>
array(2) {
["p"]=>
int(53)
["sp"]=>
int(5)
}
[1]=>
array(2) {
["p"]=>
int(53)
["sp"]=>
int(7)
}
}
}
See another php demo.

Calculate all possible combinations in array and display them in table php [duplicate]

Given a PHP array of strings, e.g.:
['peter', 'paul', 'mary']
How to generate all possible permutations of elements of this array? i.e.:
peter-paul-mary
peter-mary-paul
paul-peter-mary
paul-mary-peter
mary-peter-paul
mary-paul-peter
function pc_permute($items, $perms = array()) {
if (empty($items)) {
echo join(' ', $perms) . "<br />";
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
pc_permute($newitems, $newperms);
}
}
}
$arr = array('peter', 'paul', 'mary');
pc_permute($arr);
or
function pc_next_permutation($p, $size) {
// slide down the array looking for where we're smaller than the next guy
for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { }
// if this doesn't occur, we've finished our permutations
// the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1)
if ($i == -1) { return false; }
// slide down the array looking for a bigger number than what we found before
for ($j = $size; $p[$j] <= $p[$i]; --$j) { }
// swap them
$tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;
// now reverse the elements in between by swapping the ends
for (++$i, $j = $size; $i < $j; ++$i, --$j) {
$tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;
}
return $p;
}
$set = split(' ', 'she sells seashells'); // like array('she', 'sells', 'seashells')
$size = count($set) - 1;
$perm = range(0, $size);
$j = 0;
do {
foreach ($perm as $i) { $perms[$j][] = $set[$i]; }
} while ($perm = pc_next_permutation($perm, $size) and ++$j);
foreach ($perms as $p) {
print join(' ', $p) . "\n";
}
http://docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm
This does what you need, in place, i.e. without allocating any additional memory. It stores the resulting permutations the $results array. I am pretty confident that this is the fasted way to solve the task.
<?php
function computePermutations($array) {
$result = [];
$recurse = function($array, $start_i = 0) use (&$result, &$recurse) {
if ($start_i === count($array)-1) {
array_push($result, $array);
}
for ($i = $start_i; $i < count($array); $i++) {
//Swap array value at $i and $start_i
$t = $array[$i]; $array[$i] = $array[$start_i]; $array[$start_i] = $t;
//Recurse
$recurse($array, $start_i + 1);
//Restore old order
$t = $array[$i]; $array[$i] = $array[$start_i]; $array[$start_i] = $t;
}
};
$recurse($array);
return $result;
}
$results = computePermutations(array('foo', 'bar', 'baz'));
print_r($results);
This works in PHP>5.4. I used a anonymous function for recursion to keep the main function's interface clean.
I needed something similar and found this post while looking. Landed up writing the following which does the job.
With 8 items it works fairly quickly (a bit quicker than the examples I found online), but go beyond that and the run time ramps up rapidly. If you only need to output the results it could be made quicker and the memory use reduced massively.
print_r(AllPermutations(array('peter', 'paul', 'mary')));
function AllPermutations($InArray, $InProcessedArray = array())
{
$ReturnArray = array();
foreach($InArray as $Key=>$value)
{
$CopyArray = $InProcessedArray;
$CopyArray[$Key] = $value;
$TempArray = array_diff_key($InArray, $CopyArray);
if (count($TempArray) == 0)
{
$ReturnArray[] = $CopyArray;
}
else
{
$ReturnArray = array_merge($ReturnArray, AllPermutations($TempArray, $CopyArray));
}
}
return $ReturnArray;
}
Note that the number of permutations is the factorial of the number of items in the array. For 3 items there are 6 permutations, for 4 there are 24, for 5 there are 120, for 6 there are 720, etc.
EDIT
Came back to have a look at this and done some revisions.
Below is an improved version of this function, which uses less storage and is quicker (quicker than other solutions I have seen).
It takes the return array as a parameter, passing it through by reference. This reduces the amount of duplication of data as it runs through.
function AllPermutations($InArray, &$ReturnArray = array(), $InProcessedArray = array())
{
if (count($InArray) == 1)
{
$ReturnArray[] = array_merge($InProcessedArray, $InArray);
}
else
{
foreach($InArray as $Key=>$value)
{
$CopyArray = $InArray;
unset($CopyArray[$Key]);
AllPermutations2($CopyArray, $ReturnArray, array_merge($InProcessedArray, array($Key=>$value)));
}
}
}
I expanded a bit on the answer of Jack
function pc_permute($items, $perms = [],&$ret = []) {
if (empty($items)) {
$ret[] = $perms;
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$this->pc_permute($newitems, $newperms,$ret);
}
}
return $ret;
}
This will actually return an array with all possible permutations.
$options = ['startx','starty','startz','endx','endy','endz'];
$x = $this->pc_permute($options);
var_dump($x);
[0]=>
array(6) {
[0]=>
string(6) "startx"
[1]=>
string(6) "starty"
[2]=>
string(6) "startz"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[1]=>
array(6) {
[0]=>
string(6) "starty"
[1]=>
string(6) "startx"
[2]=>
string(6) "startz"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[2]=>
array(6) {
[0]=>
string(6) "startx"
[1]=>
string(6) "startz"
[2]=>
string(6) "starty"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[3]=>
array(6) {
[0]=>
string(6) "startz"
[1]=>
string(6) "startx"
[2]=>
string(6) "starty"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[4]=>
array(6) {
[0]=>
string(6) "starty"
[1]=>
string(6) "startz"
[2]=>
string(6) "startx"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[5]=>
array(6) {
[0]=>
string(6) "startz"
[1]=>
string(6) "starty"
[2]=>
string(6) "startx"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[6]=> ................ a lot more
I found it a bit more usefull to get an array back instead of a string. Then it's up to the using application how to handle the resutls(to join them, or something else)
Simple version with recursion and no artificial extra arguments:
function permuteArray(array $input) {
$input = array_values($input);
// permutation of 1 value is the same value
if (count($input) === 1) {
return array($input);
}
// to permute multiple values, pick a value to put in the front and
// permute the rest; repeat this with all values of the original array
$result = [];
for ($i = 0; $i < count($input); $i++) {
$copy = $input;
$value = array_splice($copy, $i, 1);
foreach (permuteArray($copy) as $permutation) {
array_unshift($permutation, $value[0]);
$result[] = $permutation;
}
}
return $result;
}
This algorithm is nice and instructive how you would do it on paper, but otherwise very inefficient as it calculates same permutations multiple times. Not to say that it is very impractical for calculating permutations of larger arrays as the space and number of calculations grow exponentially.
Recursive function to get all permutations of an array.
Call getPermutations($arr) to get an array of arrays with all the permutations.
function getPermutations ($arr)
{
assert (!empty($arr));
if (count($arr)==1)
{
return [$arr];
}
$first=array_shift($arr);
$permutations=getPermutations($arr);
$result=[];
foreach ($permutations as $permutation)
{
$result=array_merge($result, addElementInAllPositions($permutation, $first));
}
return $result;
}
function addElementInAllPositions ($arr, $element)
{
$i=0;
$result=[];
while ($i<=count($arr))
{
$result[]=array_merge(array_slice($arr,0,$i), [$element], array_slice($arr, $i));
$i++;
}
return $result;
}
Here is another variant based on this article: https://docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm
public static function get_array_orders( $arr ) {
$arr = array_values( $arr ); // Make sure array begins from 0.
$size = count( $arr ) - 1;
$order = range( 0, $size );
$i = 0;
$orders = [];
do {
foreach ( $order as $key ) {
$orders[ $i ][] = $arr[ $key ];
}
$i ++;
} while ( $order = self::get_next_array_order( $order, $size ) );
return $orders;
}
protected static function get_next_array_order( $order, $size ) {
// slide down the array looking for where we're smaller than the next guy
$i = $size - 1;
while ( isset( $order[ $i ] ) && $order[ $i ] >= $order[ $i + 1 ] ) {
$i --;
}
// if this doesn't occur, we've finished our permutations, the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1)
if ( $i == - 1 ) {
return false;
}
// slide down the array looking for a bigger number than what we found before
$j = $size;
while( $order[ $j ] <= $order[ $i ] ){
$j--;
}
// swap them
$tmp = $order[ $i ];
$order[ $i ] = $order[ $j ];
$order[ $j ] = $tmp;
// now reverse the elements in between by swapping the ends
for ( ++ $i, $j = $size; $i < $j; ++ $i, -- $j ) {
$tmp = $order[ $i ];
$order[ $i ] = $order[ $j ];
$order[ $j ] = $tmp;
}
return $order;
}
Example:
$langs = ['en', 'fr', 'ru'];
$orders = self::get_array_orders( $langs );
print_r($orders);
Outputs:
Array (
[0] => Array
(
[0] => en
[1] => fr
[2] => ru
)
[1] => Array
(
[0] => en
[1] => ru
[2] => fr
)
[2] => Array
(
[0] => fr
[1] => en
[2] => ru
)
[3] => Array
(
[0] => fr
[1] => ru
[2] => en
)
[4] => Array
(
[0] => ru
[1] => en
[2] => fr
)
[5] => Array
(
[0] => ru
[1] => fr
[2] => en
)
)

How to merge subarrays using keys and sum the values?

I'm fairly new to PHP and I'm having some trouble with arrays and combining data. I have the following array which has been created from a foreach loop:
array(1) {
[36868]=> int(3)
}
array(1) {
[2112]=> int(3)
}
array(1) {
[35901]=> int(3)
}
array(1) {
[6496]=> int(3)
}
array(1) {
[87]=> int(3)
}
array(1) {
[36868]=> int(3)
}
array(1) {
[68]=> int(3)
}
array(1) {
[9068]=> int(3)
}
array(1) {
[47]=> int(3)
}
The key in each array is a user ID, so I need to preserve this, but I only want one instance of each key and where there are duplicate keys, sum the values. Like so:
array(1) {
[36868]=> int(6)
}
array(1) {
[2112]=> int(3)
}
array(1) {
[35901]=> int(3)
}
array(1) {
[6496]=> int(3)
}
array(1) {
[87]=> int(3)
}
array(1) {
[68]=> int(3)
}
array(1) {
[9068]=> int(3)
}
array(1) {
[47]=> int(3)
}
The I've tried looping through the array:
foreach ($array as $key => &$value) {
if ($value[0] == $value[1]) {
$value[1] += $value[1];
}
}
But with no luck. I've also tried rendering the arrays differently i.e. [userid]=>1,[score]=>3 and I feel like I'm going round in circles a bit, so any help would be hugely appreciated.
$data <-- this is your original array
$result = array_reduce(
$data,
function($carry, $item) {
foreach ($item as $id => $score) {
if (array_key_exists($id, $carry)) {
$carry[$id] += $score;
} else {
$carry[$id] = $score;
}
}
return $carry;
},
[]
);
If you are sure that each item only contains 1 entry you could also simplify the callback to not use foreach:
$result = array_reduce(
$data,
function ($carry, $item) {
$score = reset($item);
$id = key($item);
if (array_key_exists($id, $carry)) {
$carry[$id] += $score;
} else {
$carry[$id] = $score;
}
return $carry;
},
[]
);
You could also keep using foreach instead:
/** foreach to create a $data array like described below and afterwards do this: **/
$result = [];
foreach($data as $row) {
$score = reset($row);
$id = key($row);
if (array_key_exists($id, $result)) {
$result[$id] += $score;
} else {
$result[$id] = $score;
}
}
This will take an array $data like this:
array(
array('1' => 3),
array('1' => 3),
array('2' => 3),
);
and creates the variable $result like this:
array(
'1' => 6,
'2' => 3,
);
Here is a clean method that will not produce Notices. When merge-summing array data the efficient method is to generate temporary keys and use the very fast isset() function. I could have used current() and key() to access the lone subarray element, but the second foreach control structure is actually faster and more compact. (Ref:
https://stackoverflow.com/a/21219594/2943403 )
Code: (Demo)
$array = [
[36868 => 3],
[2112 => 3],
[35901 => 3],
[6496 => 3],
[87 => 3],
[36868 => 3],
[68 => 3],
[9068 => 3],
[47 => 3]
];
$result = [];
foreach ($array as $subarray) {
foreach ($subarray as $k => $v) {
if (!isset($result[$k])) {
$result[$k] = $subarray;
} else {
$result[$k][$k] += $v;
}
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
36868 => 6,
),
1 =>
array (
2112 => 3,
),
2 =>
array (
35901 => 3,
),
3 =>
array (
6496 => 3,
),
4 =>
array (
87 => 3,
),
5 =>
array (
68 => 3,
),
6 =>
array (
9068 => 3,
),
7 =>
array (
47 => 3,
),
)

Combine multiple form array into 1 array

["trnx_date"]=>
array(2) {
[0]=>
string(10) "2017-01-10"
[1]=>
string(10) "2017-01-10"
}
["curr_from"]=>
array(2) {
[0]=>
string(3) "USD"
[1]=>
string(3) "PHP"
}
["curr_from_amt"]=>
array(2) {
[0]=>
string(8) "4,000.00"
[1]=>
string(8) "3,000.00"
}
["curr_to"]=>
array(2) {
[0]=>
string(3) "GBP"
[1]=>
string(3) "SAR"
}
["curr_to_amt"]=>
array(2) {
[0]=>
string(8) "3,000.00"
[1]=>
string(8) "2,000.00"
}
["amount"]=>
array(2) {
[0]=>
string(8) "7,000.00"
[1]=>
string(8) "5,000.00"
}
I have the above array which was being submitted. This input was in sets of multiple field which was generated by dynamic table row. How can I group this into 1 (one) array so that I could save in the database? Like this:
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "USD",
'curr_from_amt' => "4,000.00",
'curr_to' => "GBP",
'curr_to_amt' => "3,000.00",
'amount' => "7,000.00"
),
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "PHP",
'curr_from_amt' => "3,000.00",
'curr_to' => "SAR",
'curr_to_amt' => "2,000.00",
'amount' => "5,000.00"
),
All of the above we being populated like this:
$trnx_date = $this->input->post('trnx_date');
$curr_from = $this->input->post('curr_from');
$curr_from_amt = $this->input->post('curr_from_amt');
$curr_to = $this->input->post('curr_to');
$curr_to_amt = $this->input->post('curr_to_amt');
$amount = $this->input->post('amount');
Assuming all the sub-arrays have the same length, you can use a simple for loop that iterates over the index of one of them, and use that to access each of the sub-arrays at that index. Then combine all of them into the associative array for each customer.
$result = array();
$keys = array_keys($array);
$len = count($array[$keys[0]]); // Get the length of one of the sub-arrays
for ($i = 0; $i < $len; $i++) {
$new = array();
foreach ($keys as $k) {
$new[$k] = $array[$k][$i];
}
$result[] = $new;
}
$arr = array(
'trnx_date' => array('2017-01-10', '2017-01-10'),
'curr_from' => array('USD', 'PHP'),
'curr_from_amt' => array('4,000.00', '3,000.00'),
'curr_to' => array('GBP', 'SAR'),
'curr_to_amt' => array('3,000.00', '2,000.00'),
'amount' => array('7,000.00', '5,000.00')
);
$arr_out = array();
$arr_keys = array_keys($arr);
for($i = 0; $i < count($arr[$arr_keys[0]]); $i++) {
$new_arr = array();
foreach($arr_keys as $key => $value) {
$new_arr[$value] = $arr[$value][$i];
}
$arr_out[] = $new_arr;
}
var_dump($arr_out);
Hope it helps!
How about this?
// assume $arr is your original data array
$keys = array_keys($arr);
$result = array();
foreach($keys as $key) {
$vals = $arr[$key];
foreach($vals as $i =>$val) {
if (!is_array($result[$i]) {
$result[$i] = array();
}
$result[$i][$key] = $val;
}
}
var_dump($result);
EDIT: added array check for $result[$i]

Categories