Create rows of elements based on an array of length values - php

Is there a neat way to split an array into chunks based on an array of lengths?
Input:
$start = range(0, 30);
$length = [3, 7, 2, 12, 6];
Desired Output:
[
[0, 1, 2], // 3
[4, 5, 6, 7, 8, 9, 10], // 7
[11, 12], // 2
[13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24], // 12
[25, 26, 27, 28, 29, 30], // 6
];

Using array_splice:
$target = array(); // or use [] in PHP 5.4
foreach($length as $i) {
$target[] = array_splice($start, 0, $i);
}
Try it.
Be advised, this changes $start!

This is very easily accomplished with the following:
Code:
$target = array();
$offset = 0;
foreach ($length as $lengthValue) {
$target[] = array_slice($start, $offset, $lengthValue);
$offset += $lengthValue;
}
var_dump($target);
Explanation:
What you are doing here is using the array_slice() method (very similar to the substr) to extract the portion of the array and then inserting it into the target array. Incrementing the offset each time allows the function to remember which one to use next time.

Related

Creating a list and indexing

Given a two list. Create a third list by picking an odd-index element from the first list and even index elements from the second.
For Example:
listOne = [3, 6, 9, 12, 15, 18, 21]
listTwo = [4, 8, 12, 16, 20, 24, 28]
Expected Output:
Printing Final third list
[6, 12, 18, 4, 12, 20, 28]
I think, it will be helpful for you.
<?php
$listOne = [3, 6, 9, 12, 15, 18, 21];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$NlistOne=[];
$NlistTwo=[];
//odd-index positions from list one [6, 12, 18]
foreach ($listOne as $key => $value) {
if($key%2==1){
array_push($NlistOne, $value);
}
}
//even-index positions from list two [4, 12, 20, 28]
foreach ($listTwo as $key => $value) {
if($key%2==0){
array_push($NlistTwo, $value);
}
}
//Printing Final third list [6, 12, 18, 4, 12, 20, 28]
print_r(array_merge($NlistOne,$NlistTwo));
?>
Output will be:
Array ( [0] => 6 [1] => 12 [2] => 18 [3] => 4 [4] => 12 [5] => 20 [6] => 28 )
//init result array
//loop over listOne, using for($i=1;$i<sizeof($listOne);$i=$i+2)
//and add to result for each iteration, $resultArr[] = $listOne[$i]
//do the same with listTwo, but for($i=*0*
You can merge both of arrays and then pick all odd elements
$listOne = [3, 6, 9, 12, 15, 18, 21];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$result = [];
foreach ( array_merge($listOne, $listTwo) as $value ){
if ( $key % 2 ) {
$result[] = $value;
}
}
If array length isn't fixed, say it could contain not 7 elements, then you need to check it before merging to make it have odd number of elements
$listOne = [3, 6, 9, 12, 15, 18, 21, 777];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$result = [];
if ( count($listOne) % 2 !== 1 ) {
$listOne[] = 0;
}
foreach( array_merge($listOne, $listTwo) as $value ){
if ( $key % 2 ) {
$result[] = $value;
}
}
you don't have to loop over whole array array_filter will do this for you, Constant ARRAY_FILTER_USE_KEY will check each key for odd or for even
<?php
$a1 = [3, 6, 9, 12, 15, 18, 21];
$a2 = [4, 8, 12, 16, 20, 24, 28];
function odd($var)
{
// returns whether the input integer is odd
return $var & 1;
}
function even($var)
{
// returns whether the input integer is even
return !($var & 1);
}
$result= (array_merge(array_filter($a1, 'odd', ARRAY_FILTER_USE_KEY),array_filter($a2, 'even', ARRAY_FILTER_USE_KEY)));
output you will get
Array (
[0] => 6
[1] => 12
[2] => 18
[3] => 4
[4] => 12
[5] => 20
[6] => 28 )
Iterate over first one and take only values of odds indices, and loop again through second one and take evens indices.
$listOne = [3, 6, 9, 12, 15, 18, 21];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$res = [];
for ($i=0; $i < count($listOne); $i++) {
if($i & 1) // $i is odd.
$res[] = $listOne[$i];
}
for ($j=0; $j < count($listTwo); $j++) {
if(n % 2 === 0) // $j is even.
$res[] = $listTwo[$j];
}
Result:
echo "List One :".json_encode($listOne)."<br>";
echo "List Two :".json_encode($listTwo)."<br>";
echo "Lists Merged:".json_encode($res);
Output:*
/*
List One :[3,6,9,12,15,18,21]
List Two :[4,8,12,16,20,24,28]
Lists Merged:[6,12,18,4,12,20,28]
*/
Iterate over arrays:
take odds in array starting with index One and increment it by two.
take evens in array by starting with index Zero and increment it by two.
$listOne = [3, 6, 9, 12, 15, 18, 21]; $listTwo = [4, 8, 12, 16, 20, 24, 28];
$res = [];
for ($i=1; $i < count($listOne); $i+=2) {
$res[] = $listOne[$i];
}
for ($j=0; $j < count($listTwo); $j+=2) {
$res[] = $listTwo[$j];
}
print(json_encode($res)); // [6,12,18,4,12,20,28]

Group Array By Range Value

I have this array [1,1,2,2,2,3,4,4,5,6,6,6,7], may I group the array according to the range value, so get the final result:
'1-3' = [1,1,2,2,2,3]; // Count is 6
'4-5' = [4,4,5]; // Count is 3
'6-7' = [6,6,6,7]; // Count is 4
What you need I believe is:
function array_get_range($array, $min, $max) {
return array_filter($array, function($element) use ($min, $max) {
return $element >= $min && $element <= $max;
});
}
$array = [1,1,2,2,2,3,4,4,5,6,6,6,7];
$range13 = array_get_range($array, 1, 3); // [1, 1, 2, 2, 2, 3]
$range45 = array_get_range($array, 4, 5); // [4, 4, 5]
$range67 = array_get_range($array, 6, 7); // [6, 6, 6, 7]
Create a new array with your ranges, then iterate through the values and through the ranges inside. If the current value is inside the range, add the record to the current range:
<?php
$numbers = [1,1,2,2,2,3,4,4,5,6,6,6,7];
$counts = [];
$counts[] = ["values"=> [1, 3], "records" => []]; // first value in "values" is min, second is max
$counts[] = ["values"=> [4, 5], "records" => []];
$counts[] = ["values"=> [6, 7], "records" => []];
foreach ($numbers as $number) {
foreach ($counts as $key => &$value) {
if ($number >= $value["values"][0] && $number <= $value["values"][1]) { // if between the range, add it to the records
$value["records"][] = $number;
}
}
}
echo "<pre>";
foreach ($counts as $count) {
echo $count["values"][0]." - ".$count["values"][1]." = ".count($count["records"])." elements<br>";
}
Demo
I think array_intersect() and range() with sizeof()/count() does a cleaner job for this task. It eliminates the double-conditional.
Code: (Demo)
function count_range($array, $min, $max) {
return sizeof(array_intersect($array, range($min, $max)));
}
$array = [1, 1, 2, 2, 2, 3, 4, 4, 5, 6, 6, 6, 7];
echo count_range($array, 1, 3); // 6 from [1, 1, 2, 2, 2, 3]
echo count_range($array, 4, 4); // 2 from [4, 4]
echo count_range($array, 2, 7); // 11 from [2, 2, 2, 3, 4, 4, 5, 6, 6, 6, 7]
range() creates a whitelist array of one or more consecutive integers.
array_intersect() compares the input array and the whitelist array all at once.
sizeof() is just an alias of count() to determine how many elements were retained.

PHP reorder an array at random

I need to reorder an array at random but I am not sure what the best/cleanest/fastest way is to do this.
So what I am trying to achieve is the following. Let's say I have an array that looks like this:
$array = array(4, 4, 4, 4, 6, 6, 6, 6, 8, 8, 10, 10, 20, 40, 60);
My goal is to get something like this but at random:
$array = array(6, 4, 4, 10, 4, 6, 4, 6, 60, 6, 8, 6, 10, 40, 8, 20);
Here's what I've been trying but it doesn't seem to be working as intended:
$array = array(4, 4, 4, 4, 6, 6, 6, 6, 8, 8, 10, 10, 20, 40, 60);
$newArray = array();
$randomNumber = rand(0 , 14);
for ($x = 0; $x <= 15; $x++) {
$newArray[$x] = $array[$randomNumber];
}
Many thanks in advance to anyone who can help me out :)
Use shuffle() function.
shuffle($array);
http://php.net/manual/en/function.shuffle.php
$array = array(4, 4, 4, 4, 6, 6, 6, 6, 8, 8, 10, 10, 20, 40, 60);
Check the output of previous array
echo "<pre>";
print_r($array);
echo "</pre>";
Shuffling previous array & check output again.
shuffle($array);
print_r($array);
Now run a foreach loop like
foreach($array as $item){
echo $item;
}
Note: You don't need to store shuffle data to new array.

How to add multidimensional array values in a loop

I have 52 weeks array's and each week array has a sub array with 9 values.
now I need to add a value 0 at the begin of each array and every next week I need 1 value more.
For example (notice that the 0-8 will be in a for loop)
$vruchtzettings_week["week1"][0-8] = 1, 2, 3, 4, 5, 6, 7, 8, 9
$vruchtzettings_week["week2"][0-8] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
$vruchtzettings_week["week3"][0-8] = 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
$vruchtzettings_week["week4"][0-8] = 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Though I can't really test it, I believe this would do it for you. What you're doing is really convoluted.
$week = 1;
while ($week <= 52) {
$sum = 0;
for ($sub = 0; $sub < 9; $sub++, $week++;) {
$totaal_vruchtzetting_week[$week] = $totaal["week$week"][$sub] + $sum;
$sum += $totaal["week$week"][$sub];
}
}
Like I said, you will probably have to tweek this a little. But it will get you started.

see if 3 or more numbers match an array

Hay i have an array consisting for 6 random numbers, here's an example
[4,8,12,22,23,43]
I also have 100 arrays containing 6 numbers, these are all random a few examples could be
[5,8,15,47,32,48]
[3,4,8,12,33,42]
[8,12,26,55,43,33]
[4,63,45,23,45,55] ...
I want to see how many times (out of the array of 100) these numbers match at least 3 from the top array. As you can guess this is a lottery experiment.
As you can see array number 3 matches 3 numbers from the top array.
Any ideas how do do this? With perhaps an option to see if 4 numbers matched.
$master_array = array(4, 8, 12, 22, 23, 43);
$arrays = array(array(5, 8, 15, 47, 32, 48),
array(3, 4, 8, 12, 33, 42),
array(8, 12, 26, 55, 43, 33),
array(4, 63, 45, 23, 45, 55));
foreach ($arrays as $arr)
{
$intersect = array_intersect($master_array, $arr);
if (count($intersect)==3) print 'Match: '.print_r($arr, true).PHP_EOL;
}
maybe smth like this:
$winner = [4,8,12,22,23,43];
$arrays = //all your 100 arrays
$i = 0; // number of matches
foreach ($arrays as $array)
{
$result = array_intersect($array, $winner);
if (count($result) >= 3) $i++;
}

Categories