This question already has answers here:
Move elements using array_chunk with PHP
(4 answers)
Closed 3 years ago.
I have array like below:
$matrix = array(1, 2, 1,1, 2, 1,1, 1, 1);
how can I get array like below?
//OUTPUT:
minesweeper(matrix) = [[1, 2, 1],
[2, 1, 1],
[1, 1, 1]]
You can use array_chunk
$matrix = array(1, 2, 1,1, 2, 1,1, 1, 1);
$res = array_chunk($matrix,3);
print_r($res);
Live working example
Related
Having two arrays of authRoom and partiRoom with one same value inside them. Want to find that same value if it was matched
Found array_search function that work only with single variable
$authRoom = [8, 7, 1, 22, 13, 18, 10];
$partiRoom= [3, 6, 5, 9, 8];
I want the output to be 8 which is the same value of these two arrays
You can use array_intersect which will give you an array of the same values in both $authRoom and $partiRoom like so:
$authRoom = [8, 7, 1, 22, 13, 18, 10];
$partiRoom = [3, 6, 5, 9, 8];
$res = array_intersect($authRoom, $partiRoom);
print_r($res); // [8]
If you want to get the value 8 outside of the array, you can simply access the first value using index 0:
$res = array_intersect($authRoom, $partiRoom)[0];
echo $res; // 8
I have an array of values (non unique) and I need to work out how many times I can pull out x (e.g 3) unique items from that array.
e.g.
[5, 5, 4, 1, 2, 3, 4, 2, 1, 3, 5, 5]
What is the largest quantity of unique items of length 3 (e.g. [5, 4, 1]) I can retrieve?
For context, this is for an offer system in a shopping cart. The array of values is the product ids, and I need to know how many times I can apply a specific offer that requires 3 different items from the array of ids in order to be valid.
Thanks for any help - just ask if anything is unclear and I'll try to explain. If I've missed an existing question that answers this please let me know and I'll close this question.
Here's one way you can follow:
$basket = array(5, 5, 4, 1, 2, 3, 4, 2, 1, 3, 5, 5);
$length = 3; //unique set size
function getSetCount($basket, $length) {
$counts = array_count_values($basket); //count of each ID
$totalCount = count($basket); //count of all elements
//maximum amount of sets
$max = floor($totalCount / $length);
//since every ID can be only once in a set, it all above $max occurences won't be able to fit any set.
$reducedCounts = array_map(function ($el) use ($max) {
return min($el, $max);
}, $counts);
//final result is "all elements that should fit in sets / size of set
return floor(array_sum($reducedCounts) / $length);
}
If you would like to print them:
function printSets($basket, $length) {
$counts = array_count_values($basket); //count of each ID
while(!empty($counts)) {
arsort($counts);//reverse sort with keeping the keys
$set = array_slice(array_keys($counts),0,$length); //get the set
echo implode(',', $set) . '<br/>';
foreach($set as $id) { //reduce counts
$counts[$id]--;
}
$counts = array_filter($counts); //clean zeros
}
}
The code above may not handle proparly some edge cases. But this is the idea.
Basically array_count_values() counts values' occurences and returns an array of value => count pairs. Then its easy to manipulate this data.
If i understand you correctly:
function getChunksCount($products)
{
// get unique ids
$uniqueProducts = array_unique($products);
// count unique ids
$count = count($uniqueProducts);
// let's get the number of chucks available
$chunkSize = 3;
// round to the floor
return floor($count / $chunkSize);
}
No complex logic or processing at all. Next time try to write down what exactly needs to be done in what order, and the solution might become pretty obvious :)
You can do it using array_unique and array_slice.
$arr = [5, 5, 4, 1, 2, 3, 4, 2, 1, 3, 5, 5];
$new_arr = array_slice(array_unique($arr), 0, 3);
print_r($new_arr); //Array ( [0] => 5 [1] => 4 [2] => 1 )
You can use array_count_values.
<?php `$array = array(5, 5, 4, 1, 2, 3, 4, 2, 1, 3, 5, 5); $vals = array_count_values($array); echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>'; print_r($vals);`?>
Output is -Array ( [5] => 4 [4] => 2 1 => 2 [2] => 2 [3] => 2 )
I'm building an online store for a clothes selling company. When displaying the products on page, the user has to be able to filter the clothes by SIZE. I also show them how many clothes belong to the specific sizes.
For this porpuse I use three arrays: $size_names, $size_ids, $size_counts
The first array can hold numeric and string values together, so it could look like this:
array(1, 2, 3, 'M', 'L', 'S')
What I basically want is to sort the values within this array in the following logic:
sort the numerical elements first, ascending
sort alphabetical elements in the following order: XXS, XS, S, M, L, XL, XXL
I read about usort(), but the problem is that I need to reorder all three arrays (size_names, size_ids, size_counts) by the reordering rule of only size_names.
So I have to sort the first array, than based on the sort, I have to sort the other two.
EDIT
One possible scenario with my three arrays could be like:
$size_names = array(3, 1, M, S)
$size_ids = array(1, 2, 3, 4)
$size_counts = array(10, 8, 3, 2)
So based on the array values I can say to the visitor that there are TWO clothes that have size S, which size has the id 4. (The ID value is not shown to the visitor, only helps me building the sql for filtering.)
I currently use array_multisort:
array_multisort($size_names, $size_ids, $size_counts);
which produces the following result:
$size_names = array(1, 3, M, S)
$size_ids = array(2, 1, 3, 4)
$size_counts = array(8, 10, 3, 2)
This is half way there, because the numeric values are sorted in the desired order, but the alphabetical values are sorted alphabetically, which is not what I want.
The desired order should be:
$size_names = array(1, 3, S, M)
$size_ids = array(2, 1, 4, 3)
$size_counts = array(8, 10, 2, 3)
Replace the alphabetical elements with numbers, do the sorting and then bring the alphabetical elements back. The following is an example:
$size_names = array(3, 1, "M", "S");
$size_ids = array(1, 2, 3, 4);
$size_counts = array(10, 8, 3, 2);
$arr1 = array("XXS", "XS", "S", "M", "L", "XL", "XXL");
$arr2 = range(1001, 1007);
$size_names = str_replace($arr1, $arr2, $size_names);
array_multisort($size_names, $size_ids, $size_counts);
$size_names = str_replace($arr2, $arr1, $size_names);
DEMO
This question already has answers here:
Adding an element to the beginning of an array without changing other array keys [duplicate]
(9 answers)
Closed 8 years ago.
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
Use array_unshift(), like this
$week=[1,2,3,4,5,6,7,8,9];
array_unshift($week,0); //[0,1,2,3,4,5,6,7,8,9]
I have an array within an array, for example:
[
[0, 20, 5],
[5, 0, 15],
[5, 10, 0]
]
I need to get the max number in each column.
The max of [0 , 5 , 5] is 5, so that goes into the result array.
The max of [20, 0, 10] is 20, so that goes into the result array.
The max of [5, 15, 0] is 15, so that goes into the result array.
The final result array must contain [5, 20, 15].
First, the array has to be transposed (flip the rows and columns):
function array_transpose($arr) {
$map_args = array_merge(array(NULL), $arr);
return call_user_func_array('array_map', $map_args);
}
(taken from Is there better way to transpose a PHP 2D array? - read that question for an explanation of how it works)
Then, you can map the max function on the new array:
$maxes = array_map('max', array_transpose($arr));
Example: http://codepad.org/3gPExrhO
Output [I think this is what you meant instead of (5, 15, 20) because you said index 1 should be max of (20, 0, 10)]:
Array
(
[0] => 5
[1] => 20
[2] => 15
)
Without the splat operator, array_map() with max() will return the max value for each row. ([20, 15, 10])
With the splat operator to transpose the data structure, the max value for each column is returned.
Code: (Demo)
$array = [
[0, 20, 5],
[5, 0, 15],
[5, 10, 0]
];
var_export(
array_map('max', ...$array)
);
Output:
array (
0 => 5,
1 => 20,
2 => 15,
)