I am trying to sort it in a repeating, sequential pattern of numerical order with the largest sets first.
Sample array:
$array = [1,1,1,2,3,2,3,4,5,4,4,4,5,1,2,2,3];
In the above array, I have the highest value of 5 which appears twice so the first two sets would 1,2,3,4,5 then it would revert to the second, highest value set etc.
Desired result:
[1,2,3,4,5,1,2,3,4,5,1,2,3,4,1,2,4]
I am pretty sure I can split the array into chunks of the integer values then cherrypick an item from each subarray sequentially until there are no remaining items, but I just feel that this is going to be poor for performance and I don't want to miss a simple trick that PHP can already handle.
Here's my attempt at a very manual loop using process, the idea is to simply sort the numbers into containers for array_unshifting. I'm sure this is terrible and I'd love someone to do this in five lines or less :)
$array = array(1,1,1,2,3,2,3,4,5,4,4,4,5,1,2,2,3);
sort($array);
// Build the container array
$numbers = array_fill_keys(array_unique($array),array());
// Assignment
foreach( $array as $number )
{
$numbers[ $number ][] = $number;
}
// Worker Loop
$output = array();
while( empty( $numbers ) === false )
{
foreach( $numbers as $outer => $inner )
{
$output[] = array_shift( $numbers[ $outer ] );
if( empty( $numbers[ $outer ] ) )
{
unset( $numbers[ $outer ] );
}
}
}
var_dump( $output );
I think I'd look at this not as a sorting problem, but alternating values from multiple lists, so rather than coming up with sets of distinct numbers I'd make sets of the same number.
Since there's no difference between one 1 and another, all you actually need is to count the number of times each appears. It turns out PHP can do this for you with aaray_count_values.
$sets = array_count_values ($input);
Then we can make sure the sets are in order by sorting by key:
ksort($sets);
Now, we iterate round our sets, counting down how many times we've output each number. Once we've "drained" a set, we remove it from the list, and once we have no sets left, we're all done:
$output = [];
while ( count($sets) > 0 ) {
foreach ( $sets as $number => $count ) {
$output[] = $number;
if ( --$sets[$number] == 0 ) {
unset($sets[$number]);
}
}
}
This algorithm could be adapted for cases where the values are actually distinct but can be put into sets, by having the value of each set be a list rather than a count. Instead of -- you'd use array_shift, and then check if the length of the set was zero.
You can use only linear logic to sort using php functions. Here is optimized way to fill data structures. It can be used for streams, generators or anything else you can iterate and compare.
$array = array(1,1,1,2,3,2,3,4,5,4,4,4,5,1,2,2,3);
sort($array);
$chunks = [];
$index = [];
foreach($array as $i){
if(!isset($index[$i])){
$index[$i]=0;
}
if(!isset($chunks[$index[$i]])){
$chunks[$index[$i]]=[$i];
} else {
$chunks[$index[$i]][] = $i;
}
$index[$i]++;
}
$result = call_user_func_array('array_merge', $chunks);
print_r($result);
<?php
$array = array(1,1,1,2,3,2,3,4,5,4,4,4,5,1,2,2,3);
sort($array);
while($array) {
$n = 0;
foreach($array as $k => $v) {
if($v>$n) {
$result[] = $n = $v;
unset($array[$k]);
}
}
}
echo implode(',', $result);
Output:
1,2,3,4,5,1,2,3,4,5,1,2,3,4,1,2,4
New, more elegant, more performant, more concise answer:
Create a sorting array where each number gets its own independent counter to increment. Then use array_multisort() to sort by this grouping array, then sort by values ascending.
Code: (Demo)
$encounters = [];
foreach ($array as $v) {
$encounters[] = $e[$v] = ($e[$v] ?? 0) + 1;
}
array_multisort($encounters, $array);
var_export($array);
Or with a functional style with no global variable declarations: (Demo)
array_multisort(
array_map(
function($v) {
static $e;
return $e[$v] = ($e[$v] ?? 0) + 1;
},
$array
),
$array
);
var_export($array);
Old answer:
My advice is functionally identical to #El''s snippet, but is implemented in a more concise/modern/attractive fashion.
After ensuring that the input array is sorted, make only one pass over the array and push each re-encountered value into its next row of values. The $counter variable indicates which row (in $grouped) the current value should be pushed into. When finished looping and grouping, $grouped will have unique values in each row. The final step is to merge/flatten the rows (preserving their order).
Code: (Demo)
$grouped = [];
$counter = [];
sort($array);
foreach ($array as $v) {
$counter[$v] = ($counter[$v] ?? -1) + 1;
$grouped[$counter[$v]][] = $v;
}
var_export(array_merge(...$grouped));
I have 4 arrays, each one holds another column of a table, I would like to create one array with the data ordered per array[$i]. All arrays have the same number of values: $namesArr, $folderArr, $updatedAt, $valuesArr .
I would like my new array to be contain:
$namesArr[0], $folderArr[0], $updatedAt[0], $valuesArr[0],
$namesArr[1], $folderArr[1], $updatedAt[1], $valuesArr[1],
$namesArr[2], $folderArr[2], $updatedAt[2], $valuesArr[2],
...
I guess the solution is pretty simple, but I got stuck :(
Can anyone help?
I would do something like:
$arr = array_map(function () { return func_get_args(); },$namesArr, $folderArr, $updatedAt, $valuesArr);
You can use foreach loop to merge 4 arrays:
foreach ($namesArr as $key => $value) {
$arr[$key][] = $value;
$arr[$key][] = $folderArr[$key];
$arr[$key][] = $updatedAt[$key];
$arr[$key][] = $valuesArr[$key];
}
Thus $arr will be the merged array
<?php
$newArr = array();
for ($i = 0; $i < count($namesArr); $i++)
{
$newArr[$i][0] = $namesArr[$i];
$newArr[$i][1] = $folderArr[$i];
$newArr[$i][2] = $updatedAt[$i];
$newArr[$i][3] = $valuesArr[$i];
}
?>
Explanation
What this will do is iterate depending on how many elements there are in $namesArr.
I utilised a multidimensional array here so that the first set of square brackets is effectively the "row" in a table, and the second set of square brackets are the "column" of a table.
do the following way:
while($db->query($sql)){
$namesArr[] =$db->f('names');
$folderArr[]=$db->f('folder');
$updatedAt[]=$db->f('updated');
$valuesArr[]=$db->f('values');
}
I need a new array combining 2 array with calculation
$array1 = array(2,5,7,1);
$array2 = array(1,3,2,5);
result array should out put
$array3 = array(3,8,9,6);
is this possible in php i know array_merge function combine two array but how combine after calculation
NOTE :
this is possible in C# but i want to know can i do it php as well
If they are guaranteed to be matched in size then you can use something like this
$array3 = array();
for($x =0; $x<count($array1); $x++){
$array3[] = $array1[$x] + $array2[$x];
}
If the arrays are not guaranteed to be of the same size you can do the following
$array3 = array();
$max = max(count($array1), count($array2));
for($x =0; $x<$max; $x++){
$array3[] = (isset($array1[$x])?$array1[$x]:0)) + (isset($array2[$x])?$array2[$x]:0));
}
With the adoption of PHP 7 and it's null coalesce operator this code becomes much more readable:
$array3 = array();
$max = max(count($array1), count($array2));
for($x =0; $x<$max; $x++){
$array3[] = ($array1[$x] ?? 0) + ($array2[$x] ?? 0);
}
For this you have to use foreach loop
<?php
$array1 = array(2,5,7,1);
$array2 = array(1,3,2,5);
$array3= array();
foreach($array1 as $key=>$value)
{
$array3[$key] = $array1[$key]+$array2[$key];
}
print_r($array3)
?>
I have a PHP array:
$arr = array(1,2,3,3,4,6,6);
I want to find the location of either duplicate in each duplicate pair (either 3 and either 6) and reset that value using rand(1,8). How would I go about doing this? I essentially need to make sure all of the array values are different.
You can try
$arr = array(1,2,3,3,4,6,6);
$dup = array_diff_assoc($arr,array_unique($arr));
$v = mt_rand(1, 8);
foreach ( $dup as $k ) {
while ( in_array($v, $arr) ) {
$v = mt_rand(1, 8);
}
$arr[$k] = $v;
}
echo "<pre>";
print_r($arr);
A simple way is to record how many items are in the array, use array_unique, and finally refill the array using a rand:
$size = count($arr);
$arr = array_unique($arr);
while (count($arr) < $size) {
$arr[] = rand(1,8,$arr);
}
You'd want to repeat this until count($arr) == count(array_unique($arr)). You could also make a random function that gives random values that are not already in the array pretty easily using in_array() and a loop.
I want to know if it is possible to take an array and insert the array's values into a bigger array, multiple times, so that the values of the smaller array fill up the bigger array.
Say array1 has values ([0 => 'a'],[1 => 'b'],[2 => 'c']), and array2 can hold 8 values. So, how would I take the values of array1 and insert them into array2 continuously until array2 runs out of space, so that array2 would have the values 'a','b','c','a','b','c','a','b'?
Thanks in advance,
~Hussain~
Essentially, you want to loop over and over the small array, adding each element to the new array until it has reached the desired size.
Consider this:
$max = 8;
$Orig_Array = array('a', 'b', 'c');
$Next_Array = array();
while True
{
foreach($Orig_Array as $v)
{
$Next_Array[] = $v;
if(count($Next_Array) >= $max)
break 2;
}
}
Assuming that your input array is indexed sequentially:
$len = count($input);
$output = array();
for ($i = 0; $i < MAX_SIZE; ++$i)
$output[] = $input[$i % $len];
$a = array('a','b','c');
$desired = 8;
$b = array();
for($i=0;$i<($desired/count($a))+1;++$i) $b = array_merge($b,$a);
array_splice($b,$desired);
Or
$a = array('a','b','c');
$desired = 8;
$b = array();
for($i=0;$i<$desired/count($a);++$i) $b = array_merge($b,$a);
for($i=0;$i<($desired-count($b)-1);++$i) $b[] = $a[$i];
The first one fills up an array so that it has at least desired number of elements and cuts off the rest. The second one fills up an array up the desired number of elements modulo original array size and adds up the rest.
Here's one using the input array's internal pointer, to keep things conceptually simple:
$input = array(1, 2, 3);
$size = 32;
$output = array();
for ( $i = 0; $i < $size; $i++ ) {
$curr = current($input);
if ( $curr === false ) {
reset($input);
$curr = current($input);
}
$output[] = $curr;
next($input);
}
print_r($output);die;