Using PHP, I'm trying to break an array up into multiple arrays based on groups of values. The groups are based on the values being between 1 and 5. But here's the hard part...
I need to loop through the array and put the first set of values that are between 1 and 5 in their own array, then the next set of values that are between 1 and 5 in their own array, and so on.
But each group WON'T always include 1,2,3,4,5. Some groups could be random.
Examples:
1,1,2,2,3,4,5 - this would be a group
1,2,3,4,4,4 - this would be a group
1,2,3,3,5 - this would be a group
2,2,3,3,5 - this would be a group
So I can't just test for specific numbers.
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 1
[6] => 2
[7] => 3
[8] => 4
[9] => 4
[10] => 1
[11] => 1
[12] => 3
[13] => 4
[14] => 5
)
Any Ideas?
I would just check if the current value is larger than the previous value, and if yes, begin a new group.
$groups = array();
$groupcount = 1;
foreach( $array as $key=>$value )
{
if( $key > 0 ) // there's no "previous value" for the first entry
{
if( $array[$key] < $array[$key-1] )
{
$groupcount = $groupcount + 1;
}
}
$group[groupcount][] = $value;
}
Is this what you are looking for?
$groups = array();
$cur = array();
$prev = 0;
foreach ($numbers as $number)
{
if ($number < $prev)
{
$groups[] = $cur;
$cur = array();
}
$cur[] = $number;
$prev = $number;
}
if ($cur) $groups[] = $cur;
Untested. (Edit: corrected some obvious mistakes.)
Related
Is there an efficient way to get an array by skipping every n elements starting from the end (so that the last element is always in the result)?
Basically, I have a large array of 300k elements that I want to turn to 100k or 150k.
Sample input:
$array = array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
Test: skip every other element
$x = 1;
Expected output:
$new_array = array(1,3,5,7,9,11,13,15);
Test: skip every second element
$x = 2;
Expected output:
$new_array = array(0,3,6,9,12,15);
Test: skip every third element
$x = 3;
Expected output:
$new_array = array(3,7,11,15);
Use a for() loop with a decrementing counter to allow you to push qualifying elements into the result array starting from the end of the array. To put the result array in the original order, just call array_reverse() after the loop.
Code: (Demo)
function skipFromBack(array $array, int $skip): array {
$result = [];
for ($index = array_key_last($array); $index > -1; $index -= 1 + $skip) {
$result[] = $array[$index];
}
return array_reverse($result);
}
Alternatively, you can pre-calculate the starting index, use an incrementing counter, and avoid the extra array_reverse() call. (Demo)
function skipFromBack(array $array, int $skip): array {
$increment = $skip + 1;
$count = count($array);
$start = ($count - 1) % $increment;
$result = [];
for ($i = $start; $i < $count; $i += $increment) {
$result[] = $array[$i];
}
return $result;
}
function skip_x_elements($array, $x)
{
$newArray = [];
$skipCount = 0;
foreach ($array as $value) {
if ($skipCount === $x) {
$newArray[] = $value;
$skipCount = 0;
} else {
$skipCount++;
}
}
return $newArray;
}
This should do what you want.
Improving upon #Dieter_Reinert answer, so you can also retain the keys inside said array, here is a slightly more flexible version that better fits the original question:
function skipX($array, $x, $grab = false){
$x = (!$grab) ? $x: $x - 1;
if($x <= 0) return $array;
$count = (count($array) % $x == 0) ? 0:$x;
$temparr = [];
foreach($array as $key => $value){
if($count === $x){
$temparr[$key] = $value;
$count = 0;
}else $count++;
}
return $temparr;
}
Example:
$array = range(0, 15);
foreach ([0, 1, 2, 3] as $skip){
print_r(skipX($array, $skip));
echo "\n---\n";
}
The correct output based on the original question:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 14
[15] => 15
)
---
Array
(
[1] => 1
[3] => 3
[5] => 5
[7] => 7
[9] => 9
[11] => 11
[13] => 13
[15] => 15
)
---
Array
(
[2] => 2
[5] => 5
[8] => 8
[11] => 11
[14] => 14
)
---
Array
(
[0] => 0
[4] => 4
[8] => 8
[12] => 12
)
---
Online PHP Sandbox Demo: https://onlinephp.io/c/7db96
I have a quiz where you can use text field or radio buttons for the answers. The answers are stored in a database. None of the answers are required so people can skip questions.
Each entry is stored in a row:
Array
(
[0] => Array
(
[0] => Dave
[1] => ok
[2] => Manchester
[3] => No
)
[1] => Array
(
[0] => James
[1] => Happy
[2] => London
[3] => Yes
)
[2] => Array
(
[0] => Victoia
[2] => Leeds
)
)
Currently the question number is represented by the key. So Victoria hasn't answered question 1 or 3. My aim is to add the unanswered into the array witht the correct key value being null.
Here is my code so far but I'm struggling to get the array key position correct:
$answersArr = (array) $answers;
$row = array();
$items = array();
$numberOfQuesitons = count($headers);
foreach ($answersArr as $key=>$result) {
$answer = json_decode(stripslashes($result->answers));
$row[$key] = (array) $answer;
$single = count($row[$key]);
$currentKey = key($row[$key]);
for ($i = $single ; $i < $numberOfQuesitons; $i++) {
if ($numberOfQuesitons - $i > 0) {
if ($currentKey > 0) {
array_unshift($row[$key], null);
} else {
array_push($row[$key], null);
}
}
}
}
print_r($row);
The out put I get:
Array
(
[0] => Array
(
[0] => Admin
[1] => ok
[2] => Manchester
[3] => No
)
[1] => Array
(
[0] => Rod
[1] => Happy
[2] => London
[3] => Yes
)
[2] => Array
(
[0] => Rozi
[2] => Leeds
[3] =>
[4] =>
)
)
The last row in the array needs to look like this:
[2] => Array
(
[0] => Victoia
[1] =>
[2] => Somewhere
[3] =>
)
A little stuck here any help would be much appreciated.
Thanks
Let me say that I read through your code and have to make two assumptions: $numberOfQuesitons = 4 and $single = 2 in the case of Victoia.
Assumption is based on the fact that the name of a person is included in the result arrays and otherwise could not be derived.
So in your code at the iteration of Victoia we will have the following array to work with:
$row[$key] = [
0 => 'Victoia',
2 => 'Leeds',
];
Then at the inner for loop the following will happen (as noted in comments):
for ($i = $single; $i < $numberOfQuesitons; $i++) {
// 4 - 2 = 2, 2 > 0 = true <-- first iteration
// 4 - 3 = 1, 1 > 0 = true <-- second (and final) iteration
if ($numberOfQuesitons - $i > 0) {
// $currentKey doesn't change in this process
// and since the key is taken from the array
// $row[$key] points to, the key function will return 0 each iteration.
if ($currentKey > 0) {
// Also note that unshift will only add elements to the front of the array.
array_unshift($row[$key], null);
} else {
// Hence we drop down in this branch of the if statemtent
// as 0 > 0 evaluates to false each evaluation.
// So we start with [0] => Rozi || Victoia
// [2] => Leeds || Somewhere
// Push null thus: [3] => null
// Push null thus: [4] => null
// Hence our final result.
// Also note that push only 'pushes' elements at the end of the array.
array_push($row[$key], null);
}
}
}
To solve this we could change the logic a little bit, but personally I would modify the nested loop to the following (or something similar):
$answersArr = (array) $answers;
$row = array();
$numberOfQuesitons = count($headers);
foreach ($answersArr as $key => $result) {
$answer = json_decode(stripslashes($result->answers));
$row[$key] = (array) $answer;
// We simply create a range from 0 up to the last question number.
$all = range(0, $numberOfQuesitons - 1);
// Taking the difference between all questions and the answered
// ones will give us the missing ones.
$unAnsweredQs = array_diff($all, array_keys($row[$key]));
// Add those missing questions to the array.
foreach ($unAnsweredQs as $unAnswered) {
// Or maybe a more appropriate default.
$row[$key][$unAnswered] = null;
}
// Sort the keys, such that we respect the wanted order
// Name (key 0), Q1, Q2, ..., QN
ksort($row[$key]);
}
print_r($row);
I have an array of elements which I queried from the mongoDB.
This array has the id of a device and value of this device's consumptions.
For example there are 3 different ids -> 18,5,3 and multiple mixed values.
// first record of 18 so get value.
$row[0]["id"] = 18;
$row[0]["value"] = 100;
// not first record of 18 so ignore and move to the next record
$row[1]["id"] = 18;
$row[1]["value"] = 40;
// first record of 5 so get value.
$row[2]["id"] = 5;
$row[2]["value"] = 20;
// not first record of 18 so ignore and move to the next record
$row[3]["id"] = 18;
$row[3]["value"] = 30;
// first record of 3 so get value.
$row[4]["id"] = 3;
$row[4]["value"] = 20;
//not first record of 5 so ignore and move to the next record**
$row[5]["id"] = 5;
$row[5]["value"] = 30;
// not first record of 18 so ignore and move to the next record
$row[6]["id"] = 18;
$row[6]["value"] = 10;
...
....
What I am trying to do is loop through this $row array and get the most recent value of the id.
For example in above example what I want to return is:
id value
18 100
5 20
3 20
How can I do that kind of logic?
It can be done in several ways. The easiest one is to use a foreach:
$result = array();
foreach ($row as $i) {
if (! array_key_exists($i['id'], $result)) {
$result[$i['id']] = $i['value'];
}
}
# Verify the result
print_r($result);
The output is:
Array
(
[18] => 100
[5] => 20
[3] => 20
)
The same processing, but using array_reduce():
$result = array_reduce(
$row,
function(array $c, array $i) {
if (! array_key_exists($i['id'], $c)) {
$c[$i['id']] = $i['value'];
}
return $c;
},
array()
);
If you want to keep only the first occurrence of each 'id' then just add the values to an aggregate array - but only if they haven't been added already. Then grab the values of the aggregate array.
https://tehplayground.com/NRvw9uJF615oeh6C - press Ctrl+Enter to run
$results = array();
foreach ($row as $r) {
$id = $r['id'];
if (! array_key_exists($id, $results)) {
$results[$id] = $r;
}
}
$results = array_values($results);
print_r($results);
Array
(
[0] => Array
(
[id] => 18
[value] => 100
)
[1] => Array
(
[id] => 5
[value] => 20
)
[2] => Array
(
[id] => 3
[value] => 20
)
)
Try this
$alreadyfound = []; // empty array
$result = [];
foreach ($row as $item)
{
if (in_array($item["id"], $alreadyfound))
continue;
$alreadyfound[] = $item["id"]; // add to array
$result[] = $item;
}
The result
Array
(
[0] => Array
(
[id] => 18
[value] => 100
)
[1] => Array
(
[id] => 5
[value] => 20
)
[2] => Array
(
[id] => 3
[value] => 20
)
)
The array_unique() function is exactly what you are looking at.
See the documentation here : array_unique() documentation
Using array_column with an index key will almost do it, but it will be in the reverse order, so you can reverse the input so that it works.
$result = array_column(array_reverse($row), 'value', 'id');
I fetch data from my database and it returns 6 rows. I loop over them add them to a temporary array and then every 2 iterations I add them to a parent array so I will know have an array with sub arrays grouped by 2. Below, as you can see, I echo out each iteration for 6 results. My grouped array is only showing 2 groups of 2 when it should be 3 groups of 2. What am I doing wrong?
Note: I checked the data and the first 2 groups are correct data, but the last 2 rows are missing.
// group entries into subgroups of 2
$buffer = array();
$entries = array();
for( $i = 0; $i < $journal_entries_count; $i++ )
{
if( $i % 2 == 0 && $i > 0 )
{
$entries[] = $buffer;
unset( $buffer );
$buffer = array();
}
$buffer[] = $journal_entries[ $i ];
echo $i, '<br />';
}
0
1
2
3
4
5
Array
(
[0] => Array
(
[0] => Array
(
[journal_entry_id] => 196
[journal_entry_date] => 2014-10-24 20:01:44
[scoring_type_id] => 1
[score] => 2662.00
[wod_title] => yyyyy
[wod_date] => 2014-09-12
[strength] =>
[repscheme] =>
[benchmark] => Annie
)
[1] => Array
(
[journal_entry_id] => 197
[journal_entry_date] => 2014-10-24 20:01:44
[scoring_type_id] => 1
[score] => 196.00
[wod_title] => yyyyy
[wod_date] => 2014-09-12
[strength] =>
[repscheme] =>
[benchmark] => Badger
)
)
[1] => Array
(
[0] => Array
(
[journal_entry_id] => 195
[journal_entry_date] => 2014-10-24 20:00:19
[scoring_type_id] => 1
[score] => 300.00
[wod_title] => Koala Bear WOD
[wod_date] => 2014-10-21
[strength] =>
[repscheme] =>
[benchmark] => Amanda
)
[1] => Array
(
[journal_entry_id] => 194
[journal_entry_date] => 2014-10-24 20:00:19
[scoring_type_id] => 7
[score] => 5.20
[wod_title] => Koala Bear WOD
[wod_date] => 2014-10-21
[strength] => Back Squat
[repscheme] => 10RM
[benchmark] =>
)
)
)
Solution?
I'm not marking it as a solution yet because I'm not sure it will work in all cases,
but loop at each iteration it never hits the last one.
0 = skip - add
1 = skip - add
2 = add - add
3 = skip - add
4 = add - add
5 = skip - add
I added $journal_entries_count + 1 and the results are now correct.
Thoughts?
If $journal_entries_count is 6, then at the end of your loop, $buffer will contain two rows, but it won't have been added to $entries.
You need to add a final
$entries[] = $buffer;
after the loop. Alternatively, you could use array_chunk:
$entries = array_chunk($journal_entries, 2);
can you try it with some simpler code like this and see how you go.
$entries = array();
$journal_entries[] = 1;
$journal_entries[] = 2;
$journal_entries[] = 3;
$journal_entries[] = 4;
$journal_entries[] = 5;
while (count($journal_entries)){
$entries[] = array_slice($journal_entries,0,2);
$journal_entries = array_slice($journal_entries,2);
}
print_r($entries);
You are missing the last 2 entries because you don't add the buffer from the last loop.
You need to update your code and after the foreach loop, check if the buffer is empty or not. If it's not empty then add it to the final array.
You say that for $journal_entries_count + 1 it works, because you actually run the loop one more time and adds the final buffer from the "true" last loop.
The end code should be something like this:
$buffer = array();
$entries = array();
for( $i = 0; $i < $journal_entries_count; $i++ ) {
if( $i % 2 == 0 && $i > 0 ) {
$entries[] = $buffer;
unset( $buffer );
$buffer = array();
}
$buffer[] = $journal_entries[ $i ];
echo $i, '<br />';
}
// add any leftover buffer data
if(count($buffer) > 0) {
$entries[] = $buffer;
}
I got this array:
array (
0 => 'K.',
1 => 'Vrachtschip',
2 => 'L.',
3 => 'Gevechtsschip',
4 => 'Z.',
5 => 'Gevechtsschip',
6 => 'Kruiser',
7 => 'Slagschip',
8 => 'Bommenwerper',
9 => 'Vernietiger',
10 => 'Interceptor.',
)
of can I merge the items [0] with [1], because K. vrachtschip must be together.
same ass [2] and [3]; and [4] with [5]. if there is 1 letter and then a dot (k.) it must be merged with the following array item.
Anyone that can help me :)?
How about:
$arr = array (
'K.',
'Vrachtschip',
'L.',
'Gevechtsschip',
'Z.',
'Gevechtsschip',
'Kruiser',
'Slagschip',
'Bommenwerper',
'Vernietiger',
'Interceptor',
'B.',
);
$concat = '';
$result = array();
foreach ($arr as $elem) {
if (preg_match('/^[A-Z]\.$/', $elem)) {
$concat = $elem;
continue;
}
$result[] = $concat.$elem;
$concat = '';
}
if ($concat) $result[] = $concat;
print_r($result);
output:
Array
(
[0] => K.Vrachtschip
[1] => L.Gevechtsschip
[2] => Z.Gevechtsschip
[3] => Kruiser
[4] => Slagschip
[5] => Bommenwerper
[6] => Vernietiger
[7] => Interceptor
[8] => B.
)
Try to use a regular expression to test all entries of your array.
If an occurence is founded, concat the value of your entrie with the next.
I would try something like this:
for($idx=0, $max = count($array_in); $idx < $max; $idx++)
{
if(preg_match('/^[a-z]\.$/i', $array_in[$idx]))
{
$array_out[] = $array_in[$idx].$array_in[$idx+1];
$idx++;
}
else
{
$array_out[] = $array_in[$idx];
}
}
I'd probably do the following (pseudo code):
Create empty array for result
Iterate the original array
For each value: does it match /^[a-z]\.$/i?
If yes, see if original array contains a next element?
If yes, concatenate the two items and add to resulting array, skip next item in loop
If no (pt. 4 or 5) add directly to resulting array.